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:
ignorebreak used in a loopexit function| 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
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;
}
break statement operates on the loop, not the if-else ladder.