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

时光总嘲笑我的痴心妄想 提交于 2019-11-28 06:31:23

问题


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:\n";
    cout<<"1: Display Inventory\n";
    /*truncated*/
    cout<<"5: Exit\n";
    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<<"\ninvalid entry!\n";
            break;
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/13715131/why-does-cin-clear-fix-an-infinite-loop-caused-by-bad-input-to-cin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!