+ 1

Little help please. What if the user input a STRING here (ex. dog). How can I make an output that says "Invalid Input"?

https://code.sololearn.com/c2mYDcVsqa29/?ref=app

22nd Aug 2017, 6:32 AM
Jan Paul Echaveria
Jan Paul Echaveria - avatar
2 Antworten
+ 7
I have modified your code and added a check for string literals plus check for strings with blanks and whitespaces as well using the following code- char dummy = '\0'; if (!(cin >> x) || (cin >> ws && cin.get(dummy))) cout << "Invalid input. Try again!\n"; It is working well for me! 😇 https://code.sololearn.com/c2p1lWFV5n5i/?ref=app
22nd Aug 2017, 7:04 AM
Apoorva Shenoy Nayak
Apoorva Shenoy Nayak - avatar
+ 8
Exception handling. try { cin >> input; if (cin.fail()) throw 1; // more codes } catch(int err) { switch(err) { case 1: cin.clear(); cin.ignore(512, '\n'); cout << "Invalid input."; // more cases } }
22nd Aug 2017, 7:11 AM
Hatsy Rei
Hatsy Rei - avatar