我想检查用户是否输入了有效的浮点数。奇怪的是,似乎这可以对 an 完成int,但是当我更改代码以读取 afloat时,它会给出错误消息
error: invalid operands of types 'bool' and 'float' to binary 'operator>>'
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
#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.";
}
}
Run Code Online (Sandbox Code Playgroud)
一元运算符的优先级高于!,因此表达式>>
!std::cin >> num
Run Code Online (Sandbox Code Playgroud)
被解析为
(!std::cin) >> num
Run Code Online (Sandbox Code Playgroud)
它尝试调用operator>>(bool, float). 没有定义这样的重载,因此会出现错误。
看起来你想写
!(std::cin >> num)
Run Code Online (Sandbox Code Playgroud)
请注意,您的代码仅在感谢num( a )隐式提升int为. 实际上,您正在调用,它将整数值右移到正确的时间。这无疑不是你想要的。!std::cinboolintoperator>>(int, int)!std::cinnum
| 归档时间: |
|
| 查看次数: |
303 次 |
| 最近记录: |