Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

c++ - Why does cin.clear() fix an infinite loop caused by bad input to cin?

I've written a switch statement, and created a default which would simply say the user picked a bad option and repeat the input. I wanted to make sure that if there was an issue, it would clear the buffer first, so I used cin.sync(), but entering an 'a' for the input still caused an infinite loop. I added cin.clear() to clear the flags which gave me working code ... but my confusion is why it worked. Does cin.sync() not work if there is a fail flag?

the statement follows, truncated for brevity:

while(exitAllow == false)
{
    cout<<"Your options are:
";
    cout<<"1: Display Inventory
";
    /*truncated*/
    cout<<"5: Exit
";
    cout<<"What would you like to do? ";

    cin.clear();   //HERE IS MY CONFUSION//
    cin.sync();
    cin>>action;
    switch(action)
    {
        case 1:
                    /*truncated*/
        case 5:
            exitAllow = true;
            break;
        default:
            cout<<"
invalid entry!
";
            break;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Once you try to read and it fails, the stream is marked to be in a fail state, and all subsequent attempts to read will fail automatically until you clear the fail flag, which is done with the clear() function.

You should check the status of the stream after each read:

if (cin >> var) {
   // do something sensible
} else {
   cin.clear();
}

Otherwise the value stored in var after the last successful read will be considered to be the current input for your algorithm.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...