首页 > 解决方案 > 使用 ofstream 时崩溃

问题描述

我对以下代码有疑问。我想将数据循环写入不同的文件。但是当我在循环中实例化 ofstreams 时,我的程序会默默地崩溃。我已经把代码简化了,所以它没有做任何有用的事情。它只是演示了我无法解释的行为:

#include <iostream>
#include <fstream>

using namespace std;

int main (int argc, char* argv[])
{
  ofstream test_a("a.json");
  cout << "test a" << endl;
  
  ofstream test_b("b.json");
  cout << "test b" << endl;
  
  for (int idx = 0; idx < 3; idx++)     
     {
       cout << "test " << idx << endl;
       ofstream test("test_" + to_string(idx) + ".json");
     }
  return 0;
}

这是输出:

test a
test b
test 0

没有别的,没有错误,没有。

前两个 ofstreams 显然很好,但是循环在 cout 之后的某个地方停止。我正在使用 Windows 10 和 mingw:

gcc version 8.1.0 (x86_64-win32-seh-rev0, Built by MinGW-W64 project)

标签: c++mingw-w64ofstream

解决方案


感谢有用的评论,我发现我链接了一个标准库,该库必须来自我的编译器的旧版本。我解决了这个问题,现在它可以工作了。


推荐阅读