cin - c++, how to verify is the data input is of the correct datatype -


possible duplicate:
how validate user input double in c++?

i new c++, , have function in wanting user input double value. how go insuring value input of correct datatype? also, how error handled? @ moment have:

if(cin >> radius){}else{} 

i using `try{}catch(){}, don't think right solution issue. appreciated.

if ostream& operator>>(ostream& , t&) fails extraction of formatted data (such integer, double, float, ...), stream.fail() true , !stream evaluate true too.

so can use

cin >> radius; if(!cin){     cout << "bad value!";     cin.clear();     cin.ignore(numeric_limits<streamsize>::max(), '\n');     cin >> radius; } 

or simply

while(!(cin >> radius)){     cout << "bad value!";     cin.clear();     cin.ignore(numeric_limits<streamsize>::max(), '\n'); } 

it important ignore rest of line, since operator>> won't extract data stream anymore in wrong format. if remove

cin.ignore(numeric_limits<streamsize>::max(), '\n'); 

your loop never end, input isn't cleared standard input.

see also:


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -