Search code examples
c++validationinputclion

Trying to learn about input validation loops


In this input validation while loop, cerr is being displayed after my console output is called. It displays as "Enter rate: $Invalid Rate." For example:

Enter rate: $750
Enter rate: $Invalid Rate. 

It does the same with the do-while loop. Any advice or help?

#include <iostream>

using namespace std;
#define max_rate 50
#define max_hours 80

int main() {

   // input validation loop (loops until input is valid)
   double rate, hours;

   cout << "enter rate: $";
   cin >> rate;
   cin.ignore();

   while (rate > max_rate){
       if (rate > max_rate){
           cerr << "Invalid Rate." << endl;
       }
       cout << "enter rate: $";
       cin >> rate;
   }

   do {
       if (hours > max_hours) {
           cerr << "Invalid hours." << endl;
       }
       cout << "enter hours: ";
       cin >> hours;

       }
   while (hours > max_hours);


   double pay = rate * hours;
   cout << "$" << pay << endl;
   return 0;

Solution

  • The answer is, read first, check second, claim third. That is,

    for (;;) { // the same as while(true)
        cin >> rate;
        if (rate is valid)
            break;
        cout << "Invalid rate\n";
    }
    

    And don’t mix cout and cerr without a reason. cout delays output, accumulating data in an internal buffer, while cerr prints immediately. (but cout flushes the buffer on cin use; it is also possible to call cout.flush [or cout << flush] explicitly).