kirill2485 kirill2485 - 1 month ago 7
C++ Question

While loop not waiting for user input (while datatype is invalid)

Trying to check if cin obtained valid input (eg - no string or char in int variable), but the while loop gets stuck at an infinite loop and doesn't even wait for user input

#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;
}
}


Expected result:

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


Actual result:

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

Answer

After applying cin.clear(); you need to consume the wrong input first, before applying cin >> buyAmt; again.

Something like

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;
}