C++ Notes: Example - Celsius to Fahrenheit loop

Rather than read only one data point and terminate, as Celsius to Fahrenheit does, it's much more common to read in a loop. Here is the typical idiom for doing that.
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
// basics/c2f-loop.cpp - Celsius to Fahrenheit loop.
// Fred Swartz, 2003-10-29 

#include <iostream>
using namespace std;

int main() {
    float celsius;
    float fahrenheit;
    
    cout << "Celsius to Fahrenheit conversion." << endl;
    
    while (cin >> celsius) {                // (1)
        fahrenheit = 1.8 * celsius + 32;
        cout << "Fahrenheit = " << fahrenheit << endl;
    }
    
    return 0;
}
The text from the above example can be selected, copied, and pasted into an editor.

Notes

  1. Because the read from cin produces a value that can be tested, this loop will continue while the read is successful, and fail when there is an EOF or bad input.

    See Idiom - cin loop for more discussion of this.