I need to convert a bool to a text string. Does anyone know how to do that?
I tried to use the
(std::string)bool
syntax but it didn't work.
CodePudding user response:
std::string
does not define any conversion to/from bool
. However, operator<<
and operator>>
for I/O streams do. For example, 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 result to actually say "true"
or "false"
, you can use the std::boolalpha
manipulator, eg:
oss << std::boolapha << theBoolValue;
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:
Try with static_cast<std::string> bool