I want to check if the user input a valid float or not. Curiously, it seems that this can be done for an int, but when I change my code to read a float instead, it gives the error message
error: invalid operands of types 'bool' and 'float' to binary 'operator>>'
This is my code:
#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.";
}
}
The unary operator ! has a higher precedence than >>, so the expression
!std::cin >> num
is parsed as
(!std::cin) >> num
which attempts to call operator>>(bool, float). No such overload is defined, hence the error.
It looks like you meant to write
!(std::cin >> num)
Note that your code only "worked" when num was an int thanks to !std::cin (a bool) being implicitly promoted to an int. You were in fact calling operator>>(int, int), which right-shifted the integer value of !std::cin to the right num times. This is no doubt not what you intended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With