c++ - 动态输出文件名 (C++)

标签 c++ ofstream ostringstream

我正在尝试创建由动态索引 (d = {0,...,NUM_DEMES-1}) 下标的输出文件。目前,我只获取第一个值 (d=0) 的输出文件。

#include <sstream>
#include <string>

void Simulation::updateSimulation( double t )
{
 ...
 ofstream abundanceStream;
 ofstream abHeaderStream;     

 if ( step == 1 ) {
   for ( int d = 0; d < NUM_DEMES; d++ ) {
    abundanceStream.open( makeFilename( "Abundances_", d ).c_str(),ios::out);
    abHeaderStream.open( makeFilename( "Abundances_IDs_", d ).c_str(),ios::out);
   }
 }

 for ( int d = 0; d < NUM_DEMES; d++ ) {
   abundanceStream.open( makeFilename( "Abundances_", d ).c_str(),ios::app); 
   abHeaderStream.open( makeFilename( "Abundances_IDs_", d ).c_str(),ios::app);
 }
}

string Simulation::makeFilename( const string& basename, int index )
{
  ostringstream result;
  result << basename << index;
  return result.str();
}

这会创建 Abundances_0 和 Abundances_IDs_0,但不会创建其他内容。我可以写入那些文件。我可以很好地创建其他文件名,但文件就是不显示。

我可能遗漏了一些关于流的基本知识,但我一直无法弄清楚是什么。

编辑

以下代码打印以筛选正确的文件名:

  for ( int d = 0; d < NUM_DEMES; d++ ) {
    abundanceStream.open( makeFilename( "Abundances_", d ).c_str(),ios::app);
    abundanceStream << "stuff\n";
    cout << makeFilename( "Abundances_", d ).c_str() << endl;
    abHeaderStream.open( makeFilename( "Abundances_IDs_", d ).c_str(),ios::app);
    abHeaderStream << "more stuff\n";
    cout << makeFilename( "Abundances_IDs_", d ).c_str() << endl;
  }

但是“东西”和“更多东西”只出现在 Abundances_0 和 Abundances_IDs_0 中。

最佳答案

您总是使用相同的对象。您可以在“使用”后关闭流,也可以为每个文件使用不同的对象。

关于c++ - 动态输出文件名 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1724842/

相关文章:

c++ - 如何在 64 位应用程序中获取模块大小?

C++ 'operator>>' 中的 'std::cin >>' 有歧义

c++ ostringstream对象在返回主函数后导致未处理的异常

c++ - Visual Studio : "str() is not a member of std::ostringstream"

c++ - 二进制搜索没有返回正确的值

c++ - 插入 unordered_map<pair<int,int>, int> 抛出编译器错误

c++ - 使用C++覆盖文件中的文本

c++ - VS Express 2015 Win10 应用程序 - ifstream 无法打开文件

c++ - ifstream 和 ofstream 或 fstream 使用 in 和 out

c++ - 想要 ostringstream 修改传递的字符串