Converting bool to text in C++

前端 未结 15 2295
走了就别回头了
走了就别回头了 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:37

    C++20 std::format("{}"

    https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification claims that the default output format will be the string by default:

    auto s6 = std::format("{:6}", true);  // value of s6 is "true  "
    

    and:

    The available bool presentation types are:

    • none, s: Copies textual representation (true or false, or the locale-specific form) to the output.
    • b, B, c, d, o, x, X: Uses integer presentation types with the value static_cast(value).

    Related: std::string formatting like sprintf

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

    This post is old but now you can use std::to_string to convert a lot of variable as std::string.

    http://en.cppreference.com/w/cpp/string/basic_string/to_string

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

    C++ has proper strings so you might as well use them. They're in the standard header string. #include <string> to use them. No more strcat/strcpy buffer overruns; no more missing null terminators; no more messy manual memory management; proper counted strings with proper value semantics.

    C++ has the ability to convert bools into human-readable representations too. We saw hints at it earlier with the iostream examples, but they're a bit limited because they can only blast the text to the console (or with fstreams, a file). Fortunately, the designers of C++ weren't complete idiots; we also have iostreams that are backed not by the console or a file, but by an automatically managed string buffer. They're called stringstreams. #include <sstream> to get them. Then we can say:

    std::string bool_as_text(bool b)
    {
        std::stringstream converter;
        converter << std::boolalpha << b;   // flag boolalpha calls converter.setf(std::ios_base::boolalpha)
        return converter.str();
    }
    

    Of course, we don't really want to type all that. Fortunately, C++ also has a convenient third-party library named Boost that can help us out here. Boost has a nice function called lexical_cast. We can use it thus:

    boost::lexical_cast<std::string>(my_bool)
    

    Now, it's true to say that this is higher overhead than some macro; stringstreams deal with locales which you might not care about, and create a dynamic string (with memory allocation) whereas the macro can yield a literal string, which avoids that. But on the flip side, the stringstream method can be used for a great many conversions between printable and internal representations. You can run 'em backwards; boost::lexical_cast<bool>("true") does the right thing, for example. You can use them with numbers and in fact any type with the right formatted I/O operators. So they're quite versatile and useful.

    And if after all this your profiling and benchmarking reveals that the lexical_casts are an unacceptable bottleneck, that's when you should consider doing some macro horror.

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

    If you decide to use macros (or are using C on a future project) you should add parenthesis around the 'b' in the macro expansion (I don't have enough points yet to edit other people's content):

    #define BOOL_STR(b) ((b)?"true":"false")
    

    This is a defensive programming technique that protects against hidden order-of-operations errors; i.e., how does this evaluate for all compilers?

    1 == 2 ? "true" : "false"
    

    compared to

    (1 == 2) ? "true" : "false"
    
    0 讨论(0)
  • 2020-12-01 04:46

    Try this Macro. Anywhere you want the "true" or false to show up just replace it with PRINTBOOL(var) where var is the bool you want the text for.

    #define PRINTBOOL(x) x?"true":"false"
    
    0 讨论(0)
  • 2020-12-01 04:49

    With C++11 you might use a lambda to get a slightly more compact code and in place usage:

    bool to_convert{true};
    auto bool_to_string = [](bool b) -> std::string {
        return b ? "true" : "false";
    };
    std::string str{"string to print -> "};
    std::cout<<str+bool_to_string(to_convert);
    

    Prints:

    string to print -> true
    
    0 讨论(0)
提交回复
热议问题