3.10.2. temp2.cpp

Time: 00:04:05 | Download: Large Small | Streaming
Review

This example modifies the temp.cpp (if version) example, embedding the if-else ladder in an infinite loop. The program displays a menu allowing the user to exit the program or convert a temperature from Fahrenheit to Celsius or Celsius to Fahrenheit. If the user chooses to convert a temperature, the program prompts for a temperature and displays it in the converted selected. The loop repeats the steps until the user chooses to exit the program. The loop is infinite because while (true) never ends. An infinite loop must include an internal option for terminating the program or breaking out of the loop. The program demonstrates the following concepts and functions:

\[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

        if (choice == 'F' || choice == 'f')				// Fahrenheit to Celsius
        {
            double    f;
            cout << "Please enter the temperature in Fahrenheit: ";
            cin >> f;

            cout << "Celsius: " << (5.0 / 9.0) * (f - 32) << endl;
        }
        else if (choice == 'C' || choice == 'c')			// Celsius to Fahrenheit
        {
            double    c;
            cout << "Please enter the temperature in Celsius: ";
            cin >> c;

            cout << "Fahrenheit: " << 9.0 / 5.0 * c + 32 << endl;
        }
        else if (choice == 'E' || choice == 'e')			// exit the program
            break;							// breaks out of the while-loop
            // exit(0);							// either break or exit works here
        else
            cout << "Unrecognized choice: \"" << choice << "\"\n";
    }

    return 0;
}
temp2.cpp: infinite loop with a menu. Unlike previous versions 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 statement operates on the loop, not the if-else ladder.