C++ C++;检查输入是否为int,并重复输入,直到它为int
我现在正在做一个简单的“你多大了”计算器。但是我想检查用户是否输入了int或char。所以我做了这个:C++ C++;检查输入是否为int,并重复输入,直到它为int,c++,char,int,C++,Char,Int,我现在正在做一个简单的“你多大了”计算器。但是我想检查用户是否输入了int或char。所以我做了这个: if (!cin) { cout << "Error" << endl; cin >> year; } if(!cin){ 过去一年; } 但如果我这样做,并输入一个字符,它只是通过,不允许新的输入 参考: 这是重复的,但标准答案是: std::cin.clear(); // clears the error flags // this line
if (!cin) {
cout << "Error" << endl;
cin >> year;
}
if(!cin){
过去一年;
}
但如果我这样做,并输入一个字符,它只是通过,不允许新的输入 参考:
这是重复的,但标准答案是:
std::cin.clear(); // clears the error flags
// this line discards all the input waiting in the stream
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
它将打印错误三次。它仍然设置了标志,错误的输入仍然存在。没有循环,为什么你会期望它再次出现呢汉克斯,我将在明天再试一次!
int year;
while (!(std::cin >> year)) {
std::cin.clear(); // clears the error flags
// this line discards all the input waiting in the stream
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "error" << std::endl;
}
// do something with year
a
b
c
42