首页 文章

while循环不等待用户输入(数据类型无效时)

提问于
浏览
0

试图检查cin是否获得了有效的输入(例如 - int变量中没有字符串或char),但是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

1 回答

  • 2

    应用 cin.clear(); 之后,您需要首先使用错误的输入,然后再次应用 cin >> 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;
    }
    

相关问题