简体   繁体   English

如何在C ++中检查变量的输入数据类型?

[英]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. 那段代码是绝对错误的。

  1. iostream.h doesn't exist. iostream.h不存在。 Use #include <iostream> instead. 请改用#include <iostream> The same goes for other standard headers. 其他标准标题也是如此。
  2. You need to import the namespace 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功能的开头。
  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM