Google Code University's C++ tutorial以前有这个代码:
// 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')
跳到下一个换行符(忽略与非数字在同一行的任何其他内容,以免导致另一个解析失败)。它最多只能跳过 10000 个字符,因此代码假设用户不会输入很长的无效行。
关于c++ - 为什么我们会在读取输入后调用 cin.clear() 和 cin.ignore() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5131647/