Converting bool to text in C++(在 C++ 中将 bool 转换为文本)
问题描述
也许这是一个愚蠢的问题,但有没有办法将布尔值转换为字符串,使 1 变为true",0 变为false"?我可以只使用 if 语句,但很高兴知道是否有一种方法可以使用语言或标准库来做到这一点.另外,我是个书呆子.:)
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. :)
推荐答案
使用C++语言本身怎么样?
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;
更新:
如果您想要超过 4 行代码而没有任何控制台输出,请转到 cppreference.com 的页面讨论了 std::boolalpha 和 std::noboolalpha,它显示了控制台输出并解释了有关 API 的更多信息.
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.
另外使用std::boolalpha会修改std::cout的全局状态,你可能想恢复原来的行为转到此处了解有关恢复 std::cout 状态的更多信息.
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.
这篇关于在 C++ 中将 bool 转换为文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中将 bool 转换为文本
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
