【问题标题】:Array of Ofstream in c++C++ 中的 Ofstream 数组
【发布时间】:2012-10-11 08:35:23
【问题描述】:

我希望在我的项目中使用 41 个输出文件来在其上写入文本。首先创建一个字符串数组list 来命名这些输出文件,然后我尝试定义一个ofstream 对象数组并使用list 来命名它们,但是我得到'outfile' cannot be used as a function 的这个错误。以下是我的代码:

#include <sstream>
#include <string>
#include <iostream>
#include <fstream>
using namespace std ;
int main ()
{
  string list [41];
  int i=1;
  ofstream *outFile = new ofstream [41];

  for (i=1;i<=41 ;i++)
  {
    stringstream sstm;
    sstm << "subnode" << i;
    list[i] = sstm.str();
  }

  for (i=0;i<=41;i++)
    outFile[i] (list[i].c_str());

  i=1;
  for (i=1;i<=41;i++)
    cout << list[i] << endl;

  return 0; 
}

【问题讨论】:

  • 第一个小问题:你不应该使用 list 这是一个保留字 std::list 是一个著名的容器。其次,您需要在每个 outFile 成员上调用 open(string("somefilename_or_path")) ,例如 for (int i=0; i

标签: c++ arrays ofstream


【解决方案1】:

以下修复见下文:

  1. 除非必须,否则不要使用new(您泄漏了所有文件并且没有正确破坏它们会导致数据丢失;如果您没有正确关闭它们,ofstreams 可能不会被刷新,并且挂起的输出缓冲区会丢失)
  2. 使用正确的数组索引(从 0 开始!)
  3. 默认构造 ofstream 上调用 .open(...) 以打开文件
  4. 建议:
    • 我建议不要使用 using namespace std;(以下未更改)
    • 我建议重复使用stringstream。这是一个很好的做法
    • 更喜欢使用 C++ 风格的循环索引变量 (for (int i = ....)。这可以防止i 超出范围而引发意外。
    • 其实,与时俱进,用ranged for


#include <sstream>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
    ofstream outFile[41];

    stringstream sstm;
    for (int i=0;i<41 ;i++)
    {
        sstm.str("");
        sstm << "subnode" << i;
        outFile[i].open(sstm.str());
    }

    for (auto& o:outFile)
        cout << std::boolalpha << o.good() << endl;
}

【讨论】:

  • 一些“次”字“谢谢”无法表达一个人的真实感受。这次是那些“时代”之一!!!
  • outFile[i].open(sstm.str());应该是 outFile[i].open(sstm.str().c_str());
  • @abhi 如果你使用 c++11 就不行
  • 您可以在循环中使用 _countof(outFile) 而不是 41。至少对于 MSVC。
  • @4LegsDrivenCat 为什么不完全使用for (auto&amp; o:outFile) cout &lt;&lt; o.good() &lt;&lt; "\n";。现在是 2016 年
【解决方案2】:

你不能像你一样调用构造函数。尝试拨打outFile[i].open(list[i].c_str())。注意“打开”。

【讨论】:

  • 很抱歉,我无法理解您的评论是什么意思
  • 亲爱的 izomorphius 你的权利。我刚刚在该行编译 sehe 的代码时出错了。
  • @sehe 但 outfile 是一个动态的流数组。所以 outfile[i] 实际上是一个 ofstream,而不是指向这样的指针。还是我错过了什么?
  • 德普。我错了。当然,数组不存储指针。哎呀。对困惑感到抱歉。 (@vahidzolf 请注意,由于使用new,我的回答仍然解决了关键问题,并且我在那里测试了我的解决方案)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-26
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多