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
How about the simple:
constexpr char const* toString(bool b)
{
return b ? "true" : "false";
}
This should be fine:
const char* bool_cast(const bool b) {
return b ? "true" : "false";
}
But, if you want to do it more C++-ish:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string bool_cast(const bool b) {
ostringstream ss;
ss << boolalpha << b;
return ss.str();
}
int main() {
cout << bool_cast(true) << "\n";
cout << bool_cast(false) << "\n";
}
Use boolalpha
to print bool to string.
std::cout << std::boolalpha << b << endl;
std::cout << std::noboolalpha << b << endl;
C++ Reference
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.
As long as strings can be viewed directly as a char array it's going to be really hard to convince me that std::string
represents strings as first class citizens in C++.
Besides, combining allocation and boundedness seems to be a bad idea to me anyways.
I use a ternary in a printf like this:
printf("%s\n", b?"true":"false");
If you macro it :
B2S(b) ((b)?"true":"false")
then you need to make sure whatever you pass in as 'b'
doesn't have any side effects. And don't forget the brackets around the 'b'
as you could get compile errors.