This version of the temperature conversion program is similar to temp2.cpp but replaces the if-else-ladder with a switch-statement. As in the if-ladder version, the program must provide some way to end the loop or program, but the switch limits the options more than an if-else ladder. Compare the overall structure of the cases in the earlier calc.cpp program with the case in the following example. Ask yourself, "Why do some cases in this example create new blocks with braces but not the cases in the calc.cpp example?"
| Scale | Freezing | Boiling |
|---|---|---|
| Fahrenheit | 32 | 212 | Celsius | 0 | 100 |
#include <iostream>
using namespace std;
int main()
{
while (true) // begin infinite loop
{
cout << "F\tfor Fahrenheit to Celsius\n"; // print menu
cout << "C\tfor Celsius to Fahrenheit\n";
cout << "E\tfor Exit\n";
cout << "Select: "; // prompt
char choice;
cin >> choice; // get user choice
cin.ignore(); // discard new line
switch (choice)
{
case 'F' : // Fahrenheit to Celsius
case 'f' :
{
double f;
cout << "Please enter the temperature in Fahrenheit: ";
cin >> f;
cout << "Celsius: " << (5.0 / 9.0) * (f - 32) << endl;
break;
}
case 'C' : // Celsius to Fahrenheit
case 'c' :
{
double c;
cout << "Please enter the temperature in Celsius: ";
cin >> c;
cout << "Fahrenheit: " << 9.0 / 5.0 * c + 32 << endl;
break;
}
case 'E' : // exit the program
case 'e' :
exit(0); // only exit works here (why?)
default :
cout << "Unrecognized choice: \"" << choice << "\"\n";
break;
}
}
return 0;
}
break statements operate on individual cases, ending the switch - they do not end the infinite loop.