I’d like to do something like the following:
bool b = ...
string s = "Value of bool is: " + b ? "f" : "d";
All of the examples I’ve seen use cout, but I don’t want to print the string; just store it.
How do I do it? If possible, I’d like one example that assigns to a char * and one to a std::string.
If your compiler is new enough, it should havestd::to_string:This would of course append
"1"(fortrue) or"0"(forfalse) to your string, not"f"or"d"as you want. The reason being that ther is no overload ofstd::to_stringthat takes abooltype, so the compiler converts it to an integer value.You can of course do it in two step, first declare the string then append the value:
Or do it almost like you do now, but explicitly create the second as a
std::string:Edit: How to get a
charpointer from astd::stringThis is done with the
std::string::c_strmethod. But as noted by Pete Becker you have to be careful how you use this pointer, as it points to data inside the string object. If the object is destroyed so is the data, and the pointer, if saved, will now be invalid.