Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++, how to verify is the data input is of the correct datatype [duplicate]

Tags:

c++

cin

Possible Duplicate:
how do I validate user input as a double in C++?

I am new to C++, and I have a function in which I am wanting the user to input a double value. How would I go about insuring that the value input was of the correct datatype? Also, how would an error be handled? At the moment this is all I have:

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

I using `try{}catch(){}, but I don't think that would the right solution for this issue. Any help would be appreciated.

like image 781
Brook Julias Avatar asked Oct 04 '12 07:10

Brook Julias


People also ask

How do you validate a double value in C++?

double x; while (1) { cout << '>'; if (cin >> x) { // valid number break; } else { // not a valid number cout << "Invalid Input! Please input a numerical value." << endl; } } //do other stuff... The above code infinitely outputs the Invalid Input! statement, so its not prompting for another input.

What does Cin fail do?

cin. fail() - This function returns true when an input failure occurs. In this case it would be an input that is not an integer. If the cin fails then the input buffer is kept in an error state.

How do you check what type a variable is in C++?

To get the datatype of variable, use typeid(x). name() of typeinfo library. It returns the type name of the variable as a string.


1 Answers

If ostream& operator>>(ostream& , T&) fails the extraction of formatted data (such as integer, double, float, ...), stream.fail() will be true and thus !stream will evaluate to true too.

So you 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 is important to ignore the rest of the line, since operator>> won't extract any data from the stream anymore as it is in a wrong format. So if you remove

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

your loop will never end, as the input isn't cleared from the standard input.

See also:

  • std::basic_istream::ignore (cin.ignore)
  • std::basic_istream::fail (cin.fail())
  • std::numeric_limits (used for the maximum number of ignored characters, defined in <limits>).
like image 161
Zeta Avatar answered Sep 28 '22 18:09

Zeta