Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check the input data type of a variable in C++?

Tags:

c++

I have one doubt about how to check the data type of input variables in C++.

#include<iostream>
using namespace std;
int main()
{
    double a,b;
    cout<<"Enter two double values";
    cin>>a>>b;
    if()        //if condition false then
        cout<<"data entered is not of double type"; 
        //I'm having trouble for identifying whether data
        //is double or not how to check please help me 
}
like image 746
atinesh singh Avatar asked Apr 19 '10 10:04

atinesh singh


3 Answers

If the input cannot be converted to a double, then the failbit will set for cin. This can be tested by calling cin.fail().

 cin>>a>>b;
 if(cin.fail())
 { 
     cout<<"data entered is not of double type"; 
 }

Update: As others have pointed out, you can also use !cin instead of cin.fail(). The two are equivalent.

like image 142
Matthew T. Staebler Avatar answered Sep 23 '22 19:09

Matthew T. Staebler


That code is hopelessly wrong.

  1. iostream.h doesn’t exist. Use #include <iostream> instead. The same goes for other standard headers.
  2. You need to import the namespace std in your code (…). This can be done by putting using namespace std; at the beginning of your main function.
  3. main must have return type int, not void.

Concerning your problem, you can check whether reading a value was successful by the following code:

if (!(cin >> a))
    cout << "failure." << endl;
…
like image 40
Konrad Rudolph Avatar answered Sep 23 '22 19:09

Konrad Rudolph


Also, if my memory serves, the following shortcut should work:

if (! (cin>>a>>B)) { handle error }
like image 30
Little Bobby Tables Avatar answered Sep 24 '22 19:09

Little Bobby Tables