3

I just wanna check if the user input is float or not, if the user input a string then i want them to do certain action, it can be done with integer, but when i change it into float. it will give a message.

error: invalid operands of types 'bool' and 'float' to binary 'operator>>'|

so this is my code down below.

#include <iostream>

int main()
{
    float num;
    std::cout << "Input number:";
    std::cin >> num;
    if (!std::cin >> num){
        std::cout << "It is not float.";
    }
}
  • 2
    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

6

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 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.

Brian
  • 4,518
  • 4
  • 16
  • 34