3.10.3. temp3.cpp

Time: 00:03:38 | Download: Large Small | Streaming

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?"

\[c = {5 \over 9} (f - 32) \] \[f = {9 \over 5} c + 32 \]
Fahrenheit to Celsius and Celsius to Fahrenheit. Formulas to convert from one temperature scale to the other. The example converts the formulas to C++ expressions.

Test Cases

Scale Freezing Boiling
Fahrenheit 32 212
Celsius 0 100

Program Listing

#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;
}
temp3.cpp: infinite loop with a menu. Like the previous version (temp2) of the temperature conversion program, this version cycles or loops endlessly, printing a menu, reading input, and printing the converted temperature until the user selects the "Exit" menu option.
Notice that the break statements operate on individual cases, ending the switch - they do not end the infinite loop.