Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Check whether the user input is float or not

Tags:

c++

iostream

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.";
    }
}
like image 449
Meilianto Luffenz Avatar asked Oct 12 '25 10:10

Meilianto Luffenz


1 Answers

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.

like image 83
Brian Avatar answered Oct 15 '25 00:10

Brian