-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
  • 324
  • 1
  • 4
  • 16

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,289
  • 8
  • 22
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 ...
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190