[英]How do I check the input data type of a variable in C++?
I have one doubt about how to check the data type of input variables in C++. 我对如何在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
}
If the input cannot be converted to a double, then the failbit
will set for cin
. 如果输入无法转换为double,则
failbit
将设置为cin
。 This can be tested by calling cin.fail()
. 这可以通过调用
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()
. 更新:正如其他人指出的那样,您也可以使用
!cin
而不是cin.fail()
。 The two are equivalent. 两者是等价的。
此外,如果我的内存服务,以下快捷方式应该工作:
if (! (cin>>a>>B)) { handle error }
That code is hopelessly wrong. 那段代码是绝对错误的。
iostream.h
doesn't exist. iostream.h
不存在。 Use #include <iostream>
instead. #include <iostream>
。 The same goes for other standard headers. std
in your code (…). std
(...)。 This can be done by putting using namespace std;
using namespace std;
来完成using namespace std;
at the beginning of your main
function. main
功能的开头。 main
must have return type int
, not void
. main
必须有返回类型int
,而不是void
。 Concerning your problem, you can check whether reading a value was successful by the following code: 关于您的问题,您可以通过以下代码检查读取值是否成功:
if (!(cin >> a))
cout << "failure." << endl;
…
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.