4

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.";
    }
}
Brian61354270
  • 8,690
  • 4
  • 21
  • 43
  • 3
    By the time you've read the user's input into a `float`, it's too late to do anything about it if it turns out the user wasn't intending to input a float; the bytes have already been consumed. I'd suggest reading the user's input into a `std::string` instead, then you can inspect the contents of the string to see if it contains digits or letters, and decide how to you want to parse the string's contents based on that. – Jeremy Friesner Sep 10 '21 at 04:07
  • 2
    @JeremyFriesner Rather than scanning the string, I'd suggest passing it to `std::stof` and catching any exception. Take advantage of the standard library's definition of what a floating-point number looks like rather than reinventing the wheel. – Keith Thompson Sep 10 '21 at 04:14
  • @KeithThompson sounds good to me, although the OP may have some specific ideas about what should count as "float" or not (e.g. is "42" a float or an int? I think `std::stof()` would classify it as a float but OP might want to handle it as an int) – Jeremy Friesner Sep 10 '21 at 04:19
  • @JeremyFriesner `std::stof()` also accepts `"INFINITY"`, `"NAN"`, and a number of variations. (I'm guessing the OP can safely ignore that.) https://en.cppreference.com/w/cpp/string/basic_string/stof – Keith Thompson Sep 10 '21 at 05:51

1 Answers1

7

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.

Brian61354270
  • 8,690
  • 4
  • 21
  • 43