Home >Backend Development >C++ >How do I print boolean values in C as strings instead of integers?
When printing a boolean value to an output stream in C , the standard provides guidelines for the displayed result.
By default, std::cout displays bool values as integers, with 0 representing false and 1 for true. However, the std::boolalpha manipulator modifies this behavior, instructing the stream to display booleans as strings: false and true.
To enable this change, use std::cout << std::boolalpha;:
<code class="cpp">#include <iostream> #include <iomanip> int main() { std::cout << false << "\n"; // Prints 0 std::cout << std::boolalpha; std::cout << false << "\n"; // Prints false return 0; }
The standard also allows for localized representation of boolean values. By imbuing the stream with the appropriate locale, you can print booleans as they appear in other languages. For instance, in French, boolalpha would display faux and vrai instead of false and true.
To use this feature, imbue the stream with a locale that supports the desired language:
<code class="cpp">#include <iostream> #include <iomanip> #include <locale> int main() { std::cout.imbue(std::locale("fr")); std::cout << false << "\n"; // Prints 0 std::cout << std::boolalpha; std::cout << false << "\n"; // Prints faux return 0; }
If you require precise control over the representation of boolean values, you can create a custom std::numpunct facet. This will allow you to define the exact strings displayed for true and false values.
Here's an example for French:
#include
#include
#include
#include
#include
class my_fr : public std::numpunct< char > {
protected:
char do_decimal_point() const { return ','; }
char do_thousands_sep() const { return '.'; }
std::string do_grouping() const { return ""; }
std::string do_truename() const { return "vrai"; }
std::string do_falsename() const { return "faux"; }
};
int main() {
std::cout.imbue(std::locale(std::locale(), new my_fr));
std::cout << false << "\n"; // Prints 0
std::cout << std::boolalpha;
std::cout << false << "\n"; // Prints faux
return 0;
}The above is the detailed content of How do I print boolean values in C as strings instead of integers?. For more information, please follow other related articles on the PHP Chinese website!