Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. :)

like image 732
Jason Baker Avatar asked Aug 27 '08 02:08

Jason Baker


People also ask

How do you convert boolean to text?

1) String.valueOf() method converts boolean to String. The valueOf() is the static method of String class. The signature of valueOf() method is given below: public static String valueOf(boolean b)

Can we convert bool to string?

To convert Boolean to String in Java, use the toString() method. For this, firstly, we have declared two booleans. String str1 = new Boolean(bool1). toString(); String str2 = new Boolean(bool2).

How do you convert boolean to char in C++?

You can use the bool array as a "bit-position" array for the representation of a char. #include <iostream> using std::cout; using std::cin; using std::endl; int main(){ bool bits[] = {0, 1, 0, 0, 0, 0, 0, 1}; char c = 0; for(int i = 0; i < …

Can you use bools in C?

Syntax to Declare Boolean Data Types in C:To declare a boolean data type in C we have to use a keyword named bool followed by a variable name. bool var_name; Here, bool is the keyword denoting the data-type and var_name is the variable name. A bool takes in real 1 bit, as we need only 2 different values(0 or 1).


1 Answers

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.

like image 102
graham.reeds Avatar answered Oct 02 '22 15:10

graham.reeds