【发布时间】:2018-04-01 14:47:58
【问题描述】:
我认为我理解使用 cin.clear() 和 cin.ignore() 处理错误输入,就像在 here 中解释的那样,但在以下示例中
#include <iostream>
#include <limits>
using namespace std; //I know that this isn't good practice.
int main () {
int a, b;
while (cout << "Input some int: " && !(cin >> a)) {
cout << "Wrong datatype!\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
while (cout << "Input some int: " && !(cin >> b)) {
cout << "Wrong datatype!\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if (a > 1) cout << "Some event.\n";
if (b > 1) cout << "Some other event.\n";
return 0;
}
我想要的行为只有在不需要的输入是某个字符时才会出现。 因此,如果我输入 x 和 y,我将再次被要求输入两个 int 并获得适当的输出,如果我输入一个 char 和一个 int 两次也是如此。
但是:如果我输入 2.3,我会得到
输入一些整数:错误的数据类型!
但没有机会更正我的输入,因为结果总是输出“某些事件”。第二个提示只是立即接受浮点数。
【问题讨论】:
-
using namespace std; //I know that this isn't good practice.这是健壮、紧凑、最小程序的好习惯。 -
为什么你输入浮点数但你的数据类型是整数?
-
测试他/她的程序@Matthew.
-
请注意
2是一个有效的 int,即使2.3不是。流与有效 int 之后的内容无关。
标签: c++ if-statement io cin