簡體   English   中英

c ++中Ofstream的數組

[英]Array of Ofstream in c++

我希望在我的項目中使用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; 
}

請參閱下面的以下修復:

  1. 不要使用new除非你必須(你泄漏所有文件並且沒有正確破壞它們會導致數據丟失;如果你沒有正確關閉它們可能不會刷新,並且掛起的輸出緩沖區將會丟失)
  2. 使用正確的數組索引(從0開始!)
  3. 默認構造的 ofstream上調用.open(...)來打開文件
  4. 建議:
    • 我建議不要using namespace std; (下面未更改)
    • 我建議重用stringstream 這是很好的做法
    • 更喜歡使用C ++風格的循環索引變量( for (int i = .... )。這可以防止i有超出范圍的意外。
    • 事實上,與時俱進並使用范圍


#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(list[i].c_str()) 注意'打開'。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM