【问题标题】:While loop not waiting for user input (while datatype is invalid)While 循环不等待用户输入(而数据类型无效)
【发布时间】:2017-02-25 04:21:19
【问题描述】:

尝试检查 cin 是否获得了有效输入(例如 - int 变量中没有字符串或字符),但 while 循环卡在无限循环中,甚至不等待用户输入

#include <iostream>
#include <string>
using namespace std;
int main(){
    cout << "How many would you like to buy ? ";
    int buyAmt;
    cin >> buyAmt;
    while (!cin) {
         cin.clear();
         cin >> buyAmt;
         cout << "Sorry, you must enter an integer" << endl << endl;
    }
}

预期结果:

How many would you like to buy ? fdssd
Sorry, you must enter an integer (asks for usr input here)

实际结果:

How many would you like to buy ? fdssd
Sorry, you must enter an integer 
Sorry, you must enter an integer 
Sorry, you must enter an integer 
Sorry, you must enter an integer 
Sorry, you must enter an integer 
Sorry, you must enter an integer 

【问题讨论】:

  • 你应该std::cin.ignore()无法读取的违规字符。

标签: c++


【解决方案1】:

应用cin.clear();后,你需要先消费错误的输入,然后再应用cin &gt;&gt; buyAmt;

类似

while (!cin) {
     std::string dummy;
     cin.clear();
     cin >> dummy;
     cout << "Sorry, you must enter an integer" << endl << endl;
     cout << "How many would you like to buy ? ";
     cin >> buyAmt;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多