Home > Mobile >  Is there a way to convert a bool to a string?
Is there a way to convert a bool to a string?

Time:01-27

I need to convert a bool to a text string. Does anyone know how to do that?

I tried to use (std::string)bool syntax but it didn't work.

CodePudding user response:

The C standard does not define any direct conversions between std::string and bool. However, operator<< and operator>> for I/O streams do have such conversions defined.

In this case, you can use a std::ostringstream to format a bool into a std::string, eg:

std::ostringstream oss;
oss << theBoolValue;
std::string s = oss.str();

By default, that will output "1" for true and "0" for false. If you want the output to actually say "true" or "false" instead, you can use the std::boolalpha I/O manipulator, eg:

oss << std::boolalpha << theBoolValue;

Alternatively, in C 20 and later, you can use std::format() (in earlier versions, you can use the {fmt} library), eg:

std::string s = std::format("{}", theBoolValue); // returns "true" or "false"
std::string s = std::format("{:L}", theBoolValue); // returns the locale-specific representation
std::string s = std::format("{:d}", theBoolValue); // returns "1" or "0"
// other supported numeric formats:
// {:b} and {:B} for binary, "0b..." lowercase and "0B..." uppercase
// {:o} for octet, "0..."
// {:x} and {:X} for hex, "0x..." lowercase and "0X..." uppercase

CodePudding user response:

This is what Sam Varshavchik suggested in comment, basically, that is it:)

    bool b;
    ...
    
    printf("b is %s\n"
      , b ? "true" : "false"
      );

CodePudding user response:

#include <string>
#include <iostream>

namespace vt {
  static constexpr auto as_string(const bool x) -> std::string {
    return (x) ? "true" : "false";
  }
} // namespace vt

int main(int argc, char** argv) {
  const auto x = argv[argc] != nullptr;
  // NB: argv[argc] is always nullptr so it's false.

  // Using a turnary to initialize a std::string
  // (See: https://en.cppreference.com/w/cpp/language/operator_other)
  const auto k0 = std::string(x ? "true" : "false");
  std::cout << "k0 = std::string(x ? \"true\" : \"false\"):\t" << k0 << "\n";

  // Using a function to achieve the same.
  const auto k1 = vt::as_string(x);
  std::cout << "k1 = vt::as_string(x):\t\t\t" << k1 << "\n";

  // If you need a string but you're fine with "0"/"1" over "false"/"true"
  const auto k2 = std::to_string(x); // x is implicitly converted to int
  std::cout << "k2 = std::to_string(x):\t\t\t" << k2 << "\n";

  // If you only intend to write to a std::ostream you don't need a string.
  std::cout << "std::cout << std::boolalpha << x:\t"
            << std::boolalpha << x << std::endl;
}

Live on Compiler Explorer

  • Related