Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;检查输入是否为int,并重复输入,直到它为int_C++_Char_Int - Fatal编程技术网

C++ C++;检查输入是否为int,并重复输入,直到它为int

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

我现在正在做一个简单的“你多大了”计算器。但是我想检查用户是否输入了int或char。所以我做了这个:

 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