-1

I want to store a value in double (ex. 1234567890) but when user enter any letter ( ex. 12345a6789) my program goes hang. How can I check whether input value is legal or not?

double num;
cout<< "Enter the number:";
cin>>num;

//How to check?
if( num is illegal )
{
cout << "Error";
return;
}
else
{
//code
}
Sunil Singh
  • 214
  • 1
  • 4
  • 15

2 Answers2

2

You can get your input value as string and then use std::stod to convert to double.std::stod throws invalid_argument exception if no conversion could be performed.

Elvis Oric
  • 1,094
  • 7
  • 21
1

The number can't tell anything if the input was correct. Instead you should check the input operation itself for failing:

double num;
cout<< "Enter the number:";
if(!(cin>>num)) {
    // invalid input ...
}
πάντα ῥεῖ
  • 85,314
  • 13
  • 111
  • 183