C++在“If”语句中将数据类型与变量进行比较(if(variable == type).........)

0 c++ types boolean-expression conditional-statements c++17

如何在条件中将变量与其数据类型进行比较?在我的程序(咖啡因吸收计算器)中使用它时,它只是直接跳过任何类型不匹配的输入到最后而不显示错误语句。

一直在移动积木,但似乎没什么区别

#include <typeinfo>

double cafContent;
...

cout << "Enter milligrams of caffeine: " << endl;
cin >> cafContent;
if (typeid(cafContent) != typeid(double)) {
    cout << "Please enter a NUMBER for caffeine content." << endl;
    return 0;
}

....
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 5

变量cafContent始终为 type double,即声明和强类型的重点。

您似乎想要的是进行输入验证。这是通过检查流本身的状态来完成的最简单的方法。记住输入操作返回对流对象的引用,并且流有一个bool转换操作符,我们可以做类似的事情

cout << "Enter milligrams of caffeine: ";
while (!(cin >> cafContent))
{
    if (cin.eof())
    {
        // TODO: User wanted to terminate, handle it somehow
    }

    // An error, most likely not a number entered
    cout << "You must enter a number.\n";
    cout << "Enter milligrams of caffeine: ";

    // We must clear the state of the stream to be able to continue
    cin.clear();

    // Also since the user might have added additional stray text after the input
    // we need read it and throw it away
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

// Here a number have been entered, do something with it
Run Code Online (Sandbox Code Playgroud)