c++stringboolean

Converting bool to text in C++


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 statement, but it would be nice to know if there is a way to do that with the language or standard libraries. Plus, I'm a pedant. :)


Solution

  • How about using the C++ language itself?

    bool t = true;
    bool f = false;
    std::cout << std::noboolalpha << t << " == " << std::boolalpha << t << std::endl;        
    std::cout << std::noboolalpha << f << " == " << std::boolalpha << f << std::endl;
    

    UPDATE:

    If you want more than 4 lines of code without any console output, please go to cppreference.com's page talking about std::boolalpha and std::noboolalpha which shows you the console output and explains more about the API.

    Additionally using std::boolalpha will modify the global state of std::cout, you may want to restore the original behavior go here for more info on restoring the state of std::cout.