在 C++ 中将 bool 转换为文本

2022-01-19 00:00:00 string boolean c++

也许这是一个愚蠢的问题,但有没有办法将布尔值转换为字符串,使 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.

相关文章