谷歌代碼大學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.IGNORE()?
3 回答

catspeake
TA貢獻1111條經驗 獲得超0個贊
cin.clear()
cin
cin.ignore(10000, '\n')

Cats萌萌
TA貢獻1805條經驗 獲得超9個贊
if (!(cin >> input_var))
cin.clear();
cin.ignore(10000,'\n');
- 3 回答
- 0 關注
- 856 瀏覽
添加回答
舉報
0/150
提交
取消