C++使用 while 循环检查输入值
C++ check input value with while loop
我有以下问题。我尝试使用 while 循环检查输入值的格式。如果输入错误,我想返回并要求用户提供新的输入。但是只是跳过了此步骤,并继续执行其余代码。我该如何解决它?提前感谢!PS:学分是双倍的。
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++,如何验证数据输入的数据类型是否正确
- 如何在C++中验证用户输入是否为双精度?
您的原始代码使用此修改:
while (std::cin.fail())
{
std::cout << "Wrong input! Please enter your number again: ";
std::cin.clear();
std::cin.ignore();
std::cin >> credits;
}
正如Tejendra所提到的,cin.clear和cin.ignore 是关键。