我是一名学习C++的初学者。我遇到了一个困扰我很久的问题,那就是cin命令。在下面的程序部分中,如果我在第一个cin命令处输入错误的类型,程序将不会执行后续的任何cin命令,但将执行程序的其余部分。
//start
#include <iostream>
using namespace std;
int main()
{
int x=0;
cout << endl << "Enter an integer" << endl;
//enter integer here. If wrong type is entered, goes to else
if (cin >> x){
cout << "The value is " << x << endl;
}
else {
cout << "You made a mistake" << endl; //executes
cin.ignore();
cin.clear();
}
cout << "Check 1" << endl; //executes
cin >> x; //skips
cout << "Check 2" << endl; //executes
cin >> x; //skips
return 0;
}
//end
如果我把同样的概念放在一个循环中而不是if else语句中:
while (!(cin >> x))
当输入错误时,程序会进入一个无限循环。
请帮我解释这个现象,因为我正在跟随的教材说上面的代码应该按预期工作。
谢谢!
clear()
,然后再执行ignore()
。 - Kerrek SB