Convert bool to text in C ++

This may be a dumb question, but is there a way to convert a boolean into a string so that 1 goes 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 this with language or standard libraries. Plus, I'm a pedant. :)

+74
c ++ string boolean
Aug 27 '08 at 2:32
source share
12 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 need more than 4 lines of code without output to the console, go to the cppreference.com page, which talks about std::boolalpha and std::noboolalpha which shows console output and explains the API in more detail.

In addition, using std::boolalpha will change the global state of std::cout , you can restore the original behavior, go here for more information on restoring the state of std::cout .

+107
Aug 27 '08 at 5:10
source share

Are we talking about C ++ right? Why are we still using macros ??

The C ++ built-in functions give you the same speed as a macro, with the added benefit of type safety and parameter evaluation (which avoids the issue mentioned by Rodney and dwj.

 inline const char * const BoolToString(bool b) { return b ? "true" : "false"; } 

In addition, I have several other problems, especially with the accepted answer :)

 // this is used in C, not C++. if you want to use printf, instead include <cstdio> //#include <stdio.h> // instead you should use the iostream libs #include <iostream> // not only is this a C include, it totally unnecessary! //#include <stdarg.h> // Macros - not type-safe, has side-effects. Use inline functions instead //#define BOOL_STR(b) (b?"true":"false") inline const char * const BoolToString(bool b) { return b ? "true" : "false"; } int main (int argc, char const *argv[]) { bool alpha = true; // printf? that C, not C++ //printf( BOOL_STR(alpha) ); // use the iostream functionality std::cout << BoolToString(alpha); return 0; } 

Greetings :)




@DrPizza: Turn on a whole boost lib for the sake of function is it easy? Do you have to joke?

+64
Aug 27 '08 at 9:34
source share

C ++ has the correct lines, so you can use them. They are in the standard title bar. #include <string> to use them. No more buffer overflows strcat / strcpy; no more missing null terminators; no more dirty manual memory management; strings with the correct calculation and semantics of the correct values.

C ++ also has the ability to convert bools to human-readable representations. We saw hints of this earlier with iostream examples, but they are a bit limited because they can only transfer text to the console (or with fstreams, a file). Fortunately, C ++ designers were not complete idiots; we also have iostreams, which are not supported by the console or file, but by an automatically controlled string buffer. They are called string flows. #include <sstream> to get them. Then we can say:

 std::string bool_as_text(bool b) { std::stringstream converter; converter << std::boolalpha << b; // flag boolalpha calls converter.setf(std::ios_base::boolalpha) return converter.str(); } 

Of course, we do not want to print all this. Fortunately, C ++ also has a handy third-party library called Boost that can help us here. Boost has a wonderful lexical_cast function. We can use it this way:

 boost::lexical_cast<std::string>(my_bool) 

Now it’s true to say that this is a higher load than any macro; String streams deal with locales that may not bother you, and create a dynamic string (with memory allocation), while a macro can produce a literal string, which avoids this. But, on the other hand, the stringstream method can be used for so many conversions between print and internal representations. You can run them back; For example, boost :: lexical_cast <bool> ("true") does the right thing. You can use them with numbers and virtually any type with the right formatted I / O operators. So they are quite versatile and useful.

And if after all this your profiling and benchmarking reveals that lexical_casts is an unacceptable bottleneck, then you should consider making some kind of macro-horror.

+21
Aug 27 '08 at 9:56
source share

This should be good:

 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"; } 
+6
Aug 27 '08 at 11:08
source share

If you decide to use macros (or use C in a future project), you should add parentheses around "b" in the macro extension (I don't have enough impressions to edit other people's content):

 #define BOOL_STR(b) ((b)?"true":"false") 

This is a defensive programming that protects against hidden operations order errors; that is, how is this evaluated for all compilers?

 1 == 2 ? "true" : "false" 

compared with

 (1 == 2) ? "true" : "false" 
+4
Aug 27 '08 at 4:46
source share

I use ternar in printf as follows:

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

If you run the macro:

 B2S(b) ((b)?"true":"false") 

then you need to make sure that everything you pass as 'b' has no side effects. And don't forget the brackets around 'b' , as you may get compilation errors.

+1
Aug 27 '08 at 4:19
source share

This post is old, but now you can use std::to_string to convert a large number of variables to std::string .

http://en.cppreference.com/w/cpp/string/basic_string/to_string

0
Feb 28 '18 at 2:56
source share

Use boolalpha to print bool to string.

 std::cout << std::boolalpha << b << endl; std::cout << std::noboolalpha << b << endl; 

C ++ Link

0
May 22 '18 at 12:52
source share

In C ++ 11, you can use lambda to get a little more compact code and use it in place:

 bool to_convert{true}; auto bool_to_string = [](bool b) -> std::string { return b ? "true" : "false"; }; std::string str{"string to print -> "}; std::cout<<str+bool_to_string(to_convert); 

Print:

 string to print -> true 
0
Dec 13 '18 at 13:50
source share

I agree that a macro can best fit. I just hacked a test case (trust me that I am not good at C / C ++, but it sounded fun):

 #include <stdio.h> #include <stdarg.h> #define BOOL_STR(b) (b?"true":"false") int main (int argc, char const *argv[]) { bool alpha = true; printf( BOOL_STR(alpha) ); return 0; } 
-5
Aug 27 '08 at 2:41
source share

While strings can be considered directly as a char array, it will be very difficult for me to convince me that std::string represents strings as first-class citizens in C ++.

Also, a combination of distribution and narrow-mindedness seems like a bad idea to me.

-5
Aug 27 '08 at 13:37
source share

Try this macro. Wherever you want β€œtrue” or false to be displayed, simply replace it with PRINTBOOL (var), where var is the bool for which text is required.

 #define PRINTBOOL(x) x?"true":"false" 
-7
Aug 27 '08 at 2:42 on
source share



All Articles