我有以下问题。我尝试用 while 循环检查输入值的格式。如果输入错误,我想返回并要求用户提供新的输入。但是这一步只是被跳过了,它继续执行其余的代码。我该如何解决?提前致谢! P.S.:学分是双倍的。
cout << "Enter amount of credits: ";
cin >> credits;
while(cin.fail()){
cout<<"Wrong input! Please enter your number again: ";
cin>> credits;
}
最佳答案
您可以以非常简单的方式验证提供的输入数据类型
cout << "Enter amount of credits: ";
while(!(cin>> credits)){
cout<<"Wrong input! Please enter your number again: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
ignore
是清除标准输入所必需的,如下面的引用文献所述因为 operator>>
不会再从流中提取任何数据,因为它格式错误
更多引用可以查看
关于C++ 使用 while 循环检查输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36790246/