0

i am using a bool variable in a piece of code. When i try to access that variable from a another routine, i am reading the value as "True" or "False". Since i am directly displaying to a UI interface, i want to read that variable as 0 or 1. How can do it?

  • 1
    Ehh, Why don't you show `true` as `1` and `false` as `0` if that what you want? Not really sure what you are asking here.. – Jesper Juhl Jul 06 '20 at 15:43
  • Why not `static_cast(myBool);`? – Vinícius Jul 06 '20 at 15:47
  • 1
    Can you show us your code? How exactly a `bool` gets converted to a string depends on what you use to convert it. The standard IO streams would print it as `1`/`0` by default, rather than `true`/`false`. – HolyBlackCat Jul 06 '20 at 16:31

1 Answers1

1

If you want to convert a bool type to an int type then this is a good use for the unary plus operator:

bool b;
+b; // This is an `int` type

The proof:

#include <iostream>
#include <type_traits>
int main() {
    bool b;
    std::cout << std::boolalpha << std::is_same<int, decltype(b)>::value << '\n';
    std::cout << std::is_same<int, decltype(+b)>::value;
}
Bathsheba
  • 231,907
  • 34
  • 361
  • 483