122 lab week 4


What You Will Do In Your Lab

EOF-Controlled while loop

Here's an example of a I/O driver loop in main() that interacts with the user. The user enters a C. temperature and the program displays the corresponding F. temperature:

//Example: EOF-controlled loop

//prompt and read
cout << "enter celsius temp (cntrl-d to exit): ";
cin >> ctemp;

//EOF-controlled driver loop-- convert C. temps to F. temps
while(cin){
     //print ftemp
     cout << "\nCelsius = " << ctemp << " Fahrenheit = " << (9.0 / 5.0) * ctemp + 32.0 << endl;
     //prompt and read
     cout << "enter celsius temp (cntrl-d to exit): ";
     cin >> ctemp;
}

This is can be improved through the use of a value-returning function that meets this spec:

/* changeC2F() -----------------------------------
* returns the F. temp corresponding to c
*/
float changeC2F(float c);

Given this function, one can rewrite the loop:

//EOF-controlled driver loop-- convert C. temps to F. temps
while(cin){
     //print F. temp
     cout << "\nCelsius = " << ctemp << " Fahrenheit = " << changeC2F(ctemp) << endl;
     //prompt and read
     cout << "enter celsius temp (cntrl-d to exit): ";
     cin >> ctemp;
}

NOTE that the driver loop does the I/O, not the function. The loop reads a value, passes it to the function in a function call, and then prints the value returned by the function. The general rule is that value-returning functions do not use cin and do not use cout.

Lab Exercise

Your lab instructor will help you with the following:

  1. On paper, write a function definition for changeC2F(), and show it to your lab instructor.
  2. When it is correct, fire up emacs to edit a program, c2f.cpp, that uses your function and includes the EOF-controlled driver loop in main.