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?
This only applies to the conversions performed in the code, not to
std::cin >>. Howstd::cin >>reads scalar types is described here.For a
bool, it reads a singlelongvalue (so it stops reading at.if you pass a fractional number). If it's0, the result isfalse, otherwisetrue. But if the number is neither0nor1, it also sets an error flag, which you should be checking:For
0and1, this printssuccess, b=0and...=1respectively. For e.g.2or-1, this printsfailure, b=1.If you use
std::boolalpha, none of that happens, and instead it expects stringstrueorfalse(or others if you use a non-default locale).