C++ boolalpha confusion

C++ boolalpha confusion

本文关键字:confusion boolalpha C++      更新时间:2023-10-16

嗨,有人能解释下面的c++代码结果吗?

input: true false 1
output: false, true, true,
#include <iostream>
using namespace std;
int main ()
{
    bool c1, c2, c3;
    cin >> c1 >> c2 >> c3;
    cout << boolalpha << c1 << ", " << c2 << ", " << c3 << ", " << endl;//LINE I
    return 0;
}

请参阅此处

  • 通过调用str.setf(std::ios_base::boolalpha

务必先检查文档。

您操作的istream对象(此处为cin)需要0或1作为bool的输入,而您的输入则为true。这会导致操作失败,并在istream上设置failbit,因为您不检查输入是否失败,所以接下来对c2c3的两个赋值确实发生了,而是被跳过。因此,由于输入操作失败,c1为假。c2c3没有被修改或初始化,因此可以具有任何值。