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 转换为文本
基础教程推荐
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- c++ STL设置差异 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
