C++ 检查用户输入是否为浮点数

问题描述 投票:0回答:1

我想检查用户是否输入了有效的浮点数。奇怪的是,这似乎可以为

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.";
    }
}
c++ iostream
1个回答
6
投票

一元运算符

!
>>具有
更高的优先级
,所以表达式

!std::cin >> num

被解析为

(!std::cin) >> num

试图调用

operator>>(bool, float)
。没有定义这样的重载,因此错误。

看起来你是想写

!(std::cin >> num)

请注意,您的代码仅在

num
int
时才“有效”,这要归功于
!std::cin
隐式提升
int
。您实际上是在调用
operator>>(int, int)
,它将
!std::cin
的整数值右移
num
次。这无疑不是你想要的。

© www.soinside.com 2019 - 2024. All rights reserved.