【问题标题】:A C++ program that is abour cerr and clog runs differently in Clion and in terminal关于 cerr 和 clog 的 C++ 程序在 Clion 和终端中的运行方式不同
【发布时间】:2020-12-02 14:59:41
【问题描述】:

我正在尝试使用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++ 不同。但我不确定。 谁能告诉我为什么?

【问题讨论】:

  • 这是由 CLion 的“控制台”内部完成的缓冲和标准流的缓冲(或者更确切地说是 std::cerr 缺少缓冲)的不幸结果。
  • 对不起,我是初学者,能详细描述一下吗?如果可能的话,你能否给出一些关于如何用 Clion 修复探针的说明?谢谢。

标签: c++ iostream clion


【解决方案1】:

引擎盖下有很多东西(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;
}

阅读更多here

【讨论】:

  • 它仍然无法在 Clion 上运行。问题不在于代码。我的原始代码在终端上运行良好,但在 Clion 上运行良好。 SPD的回答给了我一个想法,可能是因为Clion中的控制台有一些不同的设置,虽然我还不是很清楚。
猜你喜欢
  • 2011-01-25
  • 2011-01-16
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
  • 2020-08-12
  • 2020-11-29
  • 1970-01-01
  • 2013-02-15
相关资源
最近更新 更多