C ++用while循环检查输入值

时间:2016-04-22 09:39:28

标签: c++

我有以下问题。我尝试使用while循环检查输入值的格式。如果输入错误,我想回来并要求用户提供新的输入。但是这个步骤刚刚被跳过,并继续使用其余的代码。我该如何解决?提前致谢! P.S。:Credits是双倍的。

cout << "Enter amount of credits: "; 
cin >> credits;
while(cin.fail()){
    cout<<"Wrong input! Please enter your number again: ";
    cin>> credits;
}

2 个答案:

答案 0 :(得分:2)

您可以以非常简单的方式验证提供的输入数据类型

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>>将不再从流中提取任何数据,因为它的格式错误

如需更多参考,请查看

  1. c++, how to verify is the data input is of the correct datatype
  2. how do I validate user input as a double in C++?

答案 1 :(得分:0)

您的原始代码适用于此修改:

I did some more debugging, and I found out that /api/Grill(my) does not work, 
maybe due to parentheses in the name? Because /api/Pasta works

正如Tejendra所说,cin.clear和cin.ignore是关键。