C++语言中cin函数的问题

Trouble with cin function in C++ language

我写了一个小测试代码:

#include <iostream>
using namespace std;

int main() {
    int a,b,c,d;
    cin>>a>>b,c>>d;
    cout<<a<<" "<<b<<" "<<c<<" "<<d;
    return 0;
}

我提供了输入:

1 2 3 4

输出为:

1 2 0 0

但在我看来,它应该会给出一些错误,因为 cin>>a>>b,c

为什么这段代码没有报错?

cin>>a>>b,c>>d;

应该是:

cin>>a>>b>>c>>d;

它没有任何错误,因为编译器将您的表达式视为:

cin>>a>>b;
c>>d;  // bit-wise shift operator

逗号是运算符,整数之间的 >> 是移位运算符(cin 使用此运算符的重载版本)。 所以你的代码相当于:

cin>>a>>b;
c>>d;

两行都有效,你只是忽略了第二次操作的结果

根据 comma operator:

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded, and its side effects are completed before evaluation of the expression E2 begins (note that a user-defined operator, cannot guarantee sequencing).

因此您的代码 cin>>a>>b,c>>d; 等同于:

cin>>a>>b;
c>>d;     // built-in bitwise shift operator. Note c and d isn't initialized yet.

格式正确。

逗号是一个有效的运算符,它分隔一个接一个执行的表达式,返回最左边的结果作为值。

所以:

a = b, c = d;

相当于:

a = b;
c = d;

因此,在您的情况下,您正在做两件独立但有效的事情:

cin >> a >> b, c >> d;

相当于:

cin >> a >> b;
c >> d;

c >> d 是整数之间有效的二进制移位运算。