如何检查用户给出的输入值不包含任何字符?
How to check input value given by user doesn't contain any characters?
我想以双精度存储一个值(例如 1234567890),但是当用户输入任何字母(例如 12345a6789)时,我的程序挂起。如何检查输入值是否合法?
double num;
cout<< "Enter the number:";
cin>>num;
//How to check?
if( num is illegal )
{
cout << "Error";
return;
}
else
{
//code
}
如果输入正确,数字无法说明任何问题。相反,您应该检查输入操作本身是否失败:
double num;
cout<< "Enter the number:";
if(!(cin>>num)) {
// invalid input ...
}
您可以将输入值设为 string
,然后使用 std::stod
转换为 double
。std::stod
throws invalid_argument
exception
如果无法执行转换。
我想以双精度存储一个值(例如 1234567890),但是当用户输入任何字母(例如 12345a6789)时,我的程序挂起。如何检查输入值是否合法?
double num;
cout<< "Enter the number:";
cin>>num;
//How to check?
if( num is illegal )
{
cout << "Error";
return;
}
else
{
//code
}
如果输入正确,数字无法说明任何问题。相反,您应该检查输入操作本身是否失败:
double num;
cout<< "Enter the number:";
if(!(cin>>num)) {
// invalid input ...
}
您可以将输入值设为 string
,然后使用 std::stod
转换为 double
。std::stod
throws invalid_argument
exception
如果无法执行转换。