我想检查用户输入的是否是有效的浮点数。奇怪的是,对于int
类型的数据,这似乎是可行的,但当我将代码更改为读取float
类型时,却出现了错误信息。
error: invalid operands of types 'bool' and 'float' to binary 'operator>>'
这是我的代码:
#include <iostream>
int main()
{
float num; // Works when num is an 'int', but not when its a 'float'
std::cout << "Input number:";
std::cin >> num;
if (!std::cin >> num){
std::cout << "It is not float.";
}
}
float
时,如果用户并不是想要输入一个float
,那么现在已经为时过晚了,字节已经被消耗掉了。我建议将用户的输入读入到一个std::string
中,然后您可以检查字符串的内容是否包含数字或字母,并根据此决定如何解析字符串的内容。 - Jeremy Friesnerstd::stof
并捕获任何异常。利用标准库对浮点数的定义,而不是重复发明轮子。 - Keith Thompsonstd::stof()
会将其分类为浮点数,但原帖作者可能希望将其处理为整数)。 - Jeremy Friesnerstd::stof()
还接受"INFINITY"
,"NAN"
和许多变体。 (我猜原帖的作者可以安全地忽略这一点。)https://en.cppreference.com/w/cpp/string/basic_string/stof - Keith Thompson