You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中取消cout << boolalpha的输出效果?

如何取消C++中boolalpha的格式化效果?

boolalpha是C++输出流的持久生效格式标志,一旦设置后,后续所有bool类型的输出都会默认使用文本形式(true/false)。要改回输出数字形式(1/0),只需在输出three和four之前,用noboolalpha重置这个标志即可。

修改后的完整代码如下:

bool one = true;
bool two = false;
bool three = true;
bool four = false;

cout << boolalpha;
cout << "value of one : " << one << endl; 
cout << "value of two : " << two << endl;

// 取消boolalpha的文本输出效果,恢复数字输出
cout << noboolalpha;
cout << "value of three : " << three << endl;
cout << "value of four : " << four;

运行后,one和two会输出true/false,three和four会输出1/0。

另外还有一种临时解决方案:不用修改流状态,直接把bool值强制转换为int类型输出,这种方式不受当前流格式标志的影响,适合仅需偶尔输出数字形式的场景:

cout << "value of three : " << static_cast<int>(three) << endl;
cout << "value of four : " << static_cast<int>(four);

内容的提问来源于stack exchange,提问作者Luigi_2000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 07:40:26