+ 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.
5 Respostas
+ 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
0
can you please mention the code in question so I can help you better way. thank you
0
Mock, what is while(true)?! Its gona be unlimited isnt?
At least SoloLearn Playground "tells" it
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
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?