Why would we call cin.clear() and cin.ignore() after reading input?

后端 未结 4 1982
小蘑菇
小蘑菇 2020-11-21 22:59

Google Code University\'s C++ tutorial used to have this code:

// Description: Illustrate the use of cin to get input
// and how to recover from errors.

#in         


        
4条回答
  •  自闭症患者
    2020-11-21 23:41

    You enter the

    if (!(cin >> input_var))
    

    statement if an error occurs when taking the input from cin. If an error occurs then an error flag is set and future attempts to get input will fail. That's why you need

    cin.clear();
    

    to get rid of the error flag. Also, the input which failed will be sitting in what I assume is some sort of buffer. When you try to get input again, it will read the same input in the buffer and it will fail again. That's why you need

    cin.ignore(10000,'\n');
    

    It takes out 10000 characters from the buffer but stops if it encounters a newline (\n). The 10000 is just a generic large value.

提交回复
热议问题