无法比较C++中的变量类型



我在一个类中有以下函数,它得到复数的实部:

double inputReal(){
double real;
cout << "Enter real part: ";
cin >> real;
bool compare = typeid(real) == typeid(double);
while (compare != true){
cout << "Incorrect input. Try another input: ";
cin >> real;
}
return real;
}

它应该检查real是否实际上是一个数字,如果real不是一个数字-它应该得到另一个输入。然而,如果我尝试输入这样的东西:"aa"或者"#@",它跳过while部分并继续输出,忽略获取虚部:

double inputImag(){
double imaginary;
cout << "Enter imaginary part: ";
cin >> imaginary;
bool compare = typeid(imaginary) == typeid(double);
while (compare != true){
cout << "Incorrect input. Try another input: ";
cin >> imaginary;
}
return imaginary;
}

输出,如果我尝试输入"aa"作为实部:

Enter real part: aa
Enter imaginary part: Absolute value of complex number: 0
Argument of complex value: 0
Program ended with exit code: 0

如果我输入正确,代码工作正常,所以我怀疑这是这些函数中类型的比较。我需要知道我做错了什么,我该如何补救。我对c++比较陌生,我的大学教授要求检查用户输入是否正确。如果问题不清楚,请随便问。

typeid(real) == typeid(double)将永远为真,因为realdouble

如果您想要检查您是否有有效的输入,您需要实际检查输入。这里有一种方法

double inputReal()
{
std::size_t end_pos{};
std::string input;
std::cout << "Enter real part: ";
while (getline(std::cin, input))              // get the full line of input
{
double real = std::stod(input, &end_pos); // convert to double 
if (end_pos == input.size())              // check to see if all of the input was converted
return real;
else
std::cout << "Incorrect input. Try another input: ";
}
}

最新更新