为什么我们在读取input后调用cin.clear()和cin.ignore()?

谷歌代码大学的C ++教程曾经有这样的代码:

// Description: Illustrate the use of cin to get input // and how to recover from errors. #include <iostream> using namespace std; int main() { int input_var = 0; // Enter the do while loop and stay there until either // a non-numeric is entered, or -1 is entered. Note that // cin will accept any integer, 4, 40, 400, etc. do { cout << "Enter a number (-1 = quit): "; // The following line accepts input from the keyboard into // variable input_var. // cin returns false if an input operation fails, that is, if // something other than an int (the type of input_var) is entered. if (!(cin >> input_var)) { cout << "Please enter numbers only." << endl; cin.clear(); cin.ignore(10000,'\n'); } if (input_var != -1) { cout << "You entered " << input_var << endl; } } while (input_var != -1); cout << "All done." << endl; return 0; } 

cin.clear()cin.ignore()的意义是什么? 为什么需要10000\n参数?

cin.clear()清除cin上的错误标志(以便将来的I / O操作能够正常工作),然后cin.ignore(10000, '\n')跳到下一个换行符(忽略与非数字相同的行,这样它不会导致另一个parsing失败)。 它只会跳过10000个字符,所以代码假设用户不会input非常长的无效行。

你input

 if (!(cin >> input_var)) 

语句如果从cin获取input时发生错误。 如果发生错误,则会设置错误标志,将来尝试获取input将会失败。 这就是你需要的原因

 cin.clear(); 

摆脱错误标志。 另外,失败的input将坐在我认为是某种缓冲区。 当您再次尝试input时,它将读取缓冲区中的相同input,并且将再次失败。 这就是你需要的原因

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

它从缓冲区中取出10000个字符,但遇到新行(\ n)时停止。 10000只是一个通用的大值。

使用cin.ignore(1000,'\n')清除缓冲区中前一个cin.get()所有字符,当它首先遇见'\ n'或1000 chars时,它将select停止。