+ 1

How to avoid cin input error when user inputs any symbols instead of numbers?

This error makes program uncontrolable until close it. And some times it just pases all cin to and, but some times it start cycling after error when need some input to stop, but it doesnt work.

23rd Jan 2017, 9:11 AM
Denis Zinkov
Denis Zinkov - avatar
5 Respuestas
+ 1
Hey BlooderDen : Source :https://code.sololearn.com/cUn1gwtUoCM3/#cpp #include <iostream> #include <string> #include <sstream> using namespace std; int main() { string input = ""; int myNumber = 0; while (true) { cout << "Please enter a valid number: "; getline(cin, input); // This code converts from string to number safely. stringstream myStream(input); if (myStream >> myNumber) break; cout << "Invalid number, please try again" << endl; } cout << "You entered: " << myNumber << endl << endl; return 0; } The program restrict non-integer values ! Try this !! Click above link to compile it in Solo, It will restrict
23rd Jan 2017, 10:00 AM
Mock
Mock - avatar
0
can you please mention the code in question so I can help you better way. thank you
23rd Jan 2017, 9:18 AM
Keshave Jat
Keshave Jat - avatar
0
Mock, what is while(true)?! Its gona be unlimited isnt? At least SoloLearn Playground "tells" it
24th Jan 2017, 8:13 PM
Denis Zinkov
Denis Zinkov - avatar
0
ok I got what you are asking for, may be you are looking for exception handling. just put you cin statement in try block and catch exception there
24th Jan 2017, 8:18 PM
Keshave Jat
Keshave Jat - avatar
0
"just put you cin statement in try block and catch exception there" Keshave Jat, tell me more about "in try block". What is it?
24th Jan 2017, 8:36 PM
Denis Zinkov
Denis Zinkov - avatar