简体   繁体   中英

why does order matters?

why is it that when i put cin.clear() then cin.ignore() the program works flawlessly, ex: i put in chars and the program doesn't bug.

but when i put cin.ignore() first then cin.clear() , the program doesn't stop sending error signals.

how does this work?

shouldn't the input be erased and the fail flag unset?

#include <iostream>

using namespace std;

class time
{
private:
int hours;


public:
void getime()
{
do
   {
   cout << "Enter hours: ";
   cin >> hours;
   if ( hours < 0 || hours > 23 || cin.fail()  )
   {
       cin.clear();
       cin.ignore(10,'\n');
       cerr << "invalid time, minutes must be between 0 and 59 " << endl;


   }
   }while(hours<0 || hours>23);
}
   };

int main()
{
    time asd;
    asd.getime();
    return 0;
}

cin.clear(); cin.ignore(10,'\\n'); clears the stream's error flags to make it readable again, and then tries to skip up to 10 characters to the end of a line.

cin.ignore(10,'\\n'); cin.clear(); first tries to skip up to 10 characters to the end of a line (which will fail and do nothing if the stream is in an error state), and then it clears the stream's error flags to make it readable again. Then you go around the loop and attempt again to read the ill-formatted data that caused it to fail last time.

If the question is, "why can't I use ignore to discard data from a stream that's in an error state" then, erm, you just can't. The way streams are designed to be used is that they go into an error state and sit there doing nothing until you either know how to fix it (and clear() them to say you're ignoring the error) or else give up and quit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM