How to check input type of variable in 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 } 
+4
source share
3 answers

If the input cannot be converted to double, then failbit will be set to cin . This can be verified 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 use !cin cin.fail() instead of cin.fail() . These are two equivalents.

+7
source

Also, if my memory is being served, the following shortcut should work:

 if (! (cin>>a>>B)) { handle error } 
+1
source

This code is hopelessly wrong.

  • iostream.h does not exist. Use #include <iostream> instead. The same goes for other standard headers.
  • You need to import the std into your code (...). This can be done by setting using namespace std; to the beginning of your main function.
  • main should have an int return type, not a void .

As for your problem, you can check if the value has been read using the following code:

 if (!(cin >> a)) cout << "failure." << endl; … 
+1
source

Source: https://habr.com/ru/post/1307335/


All Articles