https://rentry.org/PPP2_p108

// Code derived from Stroustrup's PPP2 book
// § 4.4.1.3 Switch technicalities
//  -and beginning on p 108

#include <iostream>

using std::cin;
using std::cout;

// example of bad code (a break is missing)
int main()
{
  constexpr double cm_per_inch = 2.54;  // number of centimeters in an inch
  double           length      = 1;     // length in inches or centimeters
  char             unit        = 'a';

  cout << "Please enter a length followed by a separated unit (c or i):\n";
  cin >> length >> unit;

  switch (unit) {
    case 'i': cout << length << "in == " << cm_per_inch * length << "cm\n";
    case 'c': cout << length << "cm == " << length / cm_per_inch << "in\n";
  }
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_04/main_p108.cpp && ./a.out

PrevUpNext

Edit
Pub: 29 Jan 2023 18:50 UTC
Edit: 29 Apr 2023 07:31 UTC
Views: 463