Converting bool to text in C++

前端 未结 15 2361
走了就别回头了
走了就别回头了 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 
    //#include 
    // instead you should use the iostream libs
    #include 
    
    // not only is this a C include, it's totally unnecessary!
    //#include 
    
    // 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?

提交回复
热议问题