首页 > 解决方案 > abour cerr 和 clog 的 C++ 程序在 Clion 和终端中的运行方式不同

问题描述

我正在尝试使用cerrclog不是cout发出错误消息。但是我遇到了一个问题。下面是简化版。

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 5; ++i) {
        int x;
        cin >> x;
        cout << "first" << endl;
        cerr << "second" << endl;
    }
    return 0;
}

但结果是

1
first
second
2
second
first
3
second
first
4
first
second
5
second
first

但是,如果我在Win10的cmd上使用g++编译运行,那就没问题了。

1
first
second
2
first
second
3
first
second
4
first
second
5
first
second

所以我开始怀疑有一些特定的设置使 Clion 内部编译运行环境与 g++ 不同。但我不确定。谁能告诉我为什么?

标签: c++iostreamclion

解决方案


引擎盖下有很多东西(SPD 在评论中提到了一些,但不是全部 - 中间有一个 pty-pipe)。但这只是工作:

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 5; ++i) {
        int x;
        cin >> x;
        cout.flush();
        cerr.flush();
        cout << "first" << endl;
        cout.flush();
        cerr << "second"<< endl;
        cerr.flush();
    }
    return 0;
}

在这里阅读更多。


推荐阅读