Does anybody know how to prevent input of integer input to string variables & vice versa?
If there is not a proper way then any good tips or tricks are also very much appreciated! :^)
Does anybody know how to prevent input of integer input to string variables & vice versa?
If there is not a proper way then any good tips or tricks are also very much appreciated! :^)
Code:#include<iostream> #include<limits> using namespace std; int main() { int n; while(!(cin>>n)) { cout<<"Only ints allowed\n"; cin.clear(); cin.ignore(numeric_limits<int>::max(),'\n'); } cout<<n<<endl; return 0; }
Last edited by manasij7479; 12-06-2011 at 05:41 PM.
You read everything as a string, then try to validate it as "looking like an int", then try to convert it to see if it really is an int.
For example, "1234567890987654321234567890987654321" might look like an int, but it would likely overflow most of the standard sizes of int you're likely to see currently.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Wouldn't that be a roundabout way ? (assuming that the conversion to an object will require stringstreams)
First you take data from the input stream to a string....then for easy checking, a stringstream has to be made ...and then from it, you could input into a particular type...checking first.
What is wrong with doing that directly from the input stream ?
> What is wrong with doing that directly from the input stream ?
Because you simultaneously have to check for whether there is any left-over crap from whatever the user typed in, and also check that the conversion itself was successful.
By the time you've "fully engineered" ever possible outcome from using cin >> var, you're not looking at that much difference in code.
However, what will be evident however is how much more complicated the code will be (therefore more error prone).
I suggest you try it, just to compare.
A really good "stress" test is
myprog.exe < myprog.exe
Crappy handling of errors usually shows up at some point.
But good code should just complain (perhaps complain a lot), but would otherwise exit without crashing.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.