在 C++ 中将 bool 转换为文本 [英] Converting bool to text in C++

查看:22
本文介绍了在 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::boolalphastd::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 转换为文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆