我希望我的代码只输入整数。下面的代码正确地完成了它的工作,并在未使用整数时询问用户输入。但是,添加代码后:
while ( ! ( cin >> x ))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Enter a number: ";
}
进入下面的代码,它仅在我先输入非整数时才有效。否则,如果我先输入一个 int,则程序不会继续执行下一条语句,也不会执行任何操作。我的理由是,如果 x = int 则不会启动 while 循环。那么为什么添加代码会弄乱剩余的代码。
#include <iostream>
#include <limits>
using namespace std;
main ()
{
cout << "Enter a number: ";
int x, y;
cin >> x;
while ( ! ( cin >> x ))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Enter a number: ";
}
cout << "Enter a number: ";
cin >> y;