c++booleanvisual-studio-2022iostreamcin

Surprising results when reading a bool with std::cin and entering decimal numbers as input


I was learning about bool variables. I learned that non-zero values are considered true, and when I used cin to assign 2 to a bool, the result was true, as expected. But when I used 0.1, the result was false. Why is that?

I have tried other numbers such as 1.1, -1.1 0.5 -0.5. My understanding is that when the absolute value is >= 1, then the result is true, and otherwise false. I don't know if this is correct, but if it is, then how to reconcile it with the "nonzero values are truthy" rule?


Solution

  • I learned that non-zero values are considered true

    This only applies to the conversions performed in the code, not to std::cin >>. How std::cin >> reads scalar types is described here.

    For a bool, it reads a single long value (so it stops reading at . if you pass a fractional number). If it's 0, the result is false, otherwise true. But if the number is neither 0 nor 1, it also sets an error flag, which you should be checking:

    #include <iostream>
    
    int main()
    {
        bool b = false;
    
        if (std::cin >> b)
            std::cout << "success, b=" << b << '\n';
        else
            std::cout << "failure, b=" << b << '\n';
    }
    

    For 0 and 1, this prints success, b=0 and ...=1 respectively. For e.g. 2 or -1, this prints failure, b=1.

    If you use std::boolalpha, none of that happens, and instead it expects strings true or false (or others if you use a non-default locale).