Meilianto Luffenz
Meilianto Luffenz

Reputation: 99

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

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.";
    }
}

Upvotes: 4

Views: 343

Answers (1)

Brian61354270
Brian61354270

Reputation: 14423

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.

Upvotes: 8

Related Questions