Converting bool to text in C++

前端 未结 15 2296
走了就别回头了
走了就别回头了 2020-12-01 04:17

Maybe this is a dumb question, but is there any way to convert a boolean value to a string such that 1 turns to \"true\" and 0 turns to \"false\"? I could just use an if st

相关标签:
15条回答
  • 2020-12-01 04:52

    We're talking about C++ right? Why on earth are we still using macros!?

    C++ inline functions give you the same speed as a macro, with the added benefit of type-safety and parameter evaluation (which avoids the issue that Rodney and dwj mentioned.

    inline const char * const BoolToString(bool b)
    {
      return b ? "true" : "false";
    }
    

    Aside from that I have a few other gripes, particularly with the accepted answer :)

    // this is used in C, not C++. if you want to use printf, instead include <cstdio>
    //#include <stdio.h>
    // instead you should use the iostream libs
    #include <iostream>
    
    // not only is this a C include, it's totally unnecessary!
    //#include <stdarg.h>
    
    // Macros - not type-safe, has side-effects. Use inline functions instead
    //#define BOOL_STR(b) (b?"true":"false")
    inline const char * const BoolToString(bool b)
    {
      return b ? "true" : "false";
    }
    
    int main (int argc, char const *argv[]) {
        bool alpha = true;
    
        // printf? that's C, not C++
        //printf( BOOL_STR(alpha) );
        // use the iostream functionality
        std::cout << BoolToString(alpha);
        return 0;
    }
    

    Cheers :)


    @DrPizza: Include a whole boost lib for the sake of a function this simple? You've got to be kidding?

    0 讨论(0)
  • 2020-12-01 04:52

    Without dragging ostream into it:

    constexpr char const* to_c_str(bool b) {
       return  
        std::array<char const*, 2>{"false", "true "}[b]
       ;
    };
    
    0 讨论(0)
  • 2020-12-01 04:53

    I agree that a macro might be the best fit. I just whipped up a test case (believe me I'm no good with C/C++ but this sounded fun):

    #include <stdio.h>
    #include <stdarg.h>
    
    #define BOOL_STR(b) (b?"true":"false")
    
    int main (int argc, char const *argv[]) {
        bool alpha = true;
        printf( BOOL_STR(alpha) );
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题