...

View Full Version : Validating Input...



Code Wizard
04-11-2004, 05:46 PM
In C++ if an integer value is expected,and the user enters a character,what value shall the variable actually take?



int n;
cout<<"n=";
cin>>n;



And also,what sort of validation is it best to use?
For example,this won't work:



int n;
do
cout<<"Enter a number:";
while(!(cin>>n));



:confused:

Mhtml
04-12-2004, 03:04 AM
Well, I hardly ever use console stuff but I believe that you can just do it like how you have done except instead of !cin>>n using cin.fail (it's a bool)..



int n;
do
cout<<"Enter a number:";
cin>>n;
while(cin.fail);


As for the value the variable will take when a char is entered, I don't think it will take any value. It isn't initialized in your example so it probably has some random number in it.

Code Wizard
04-12-2004, 11:01 PM
Hmm..well it's quite odd that !cin>>n doesn't work,it should be working coz cin returns a bool value depending on it's succes in reading the value...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum