C++ 在语句中比较数据类型和变量"If"(如果(变量==类型)...........)



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

一直在移动区块,但似乎没有什么不同

#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;
}
....

变量cafContent始终为类型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

最新更新