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:
std::basic_istream::ignore
(cin.ignore
)std::basic_istream::fail
(cin.fail()
)std::numeric_limits
(used maximum number of ignored characters, defined in<limits>
).
Comments
Post a Comment