0

文字列クラスへのポインターの配列があり、ファイルから各ポインターに行をコピーする必要がありますが、その方法がわかりません。

void Document::loadFile(string iFileExt){
  ioFile = new fstream(iFileExt.c_str(), ios::in);
  int i = 0;
  string row;
  string *content;

  if (ioFile->fail()){
    cerr << "File failed to open for read" << endl;
    exit(69);
  }

  while(ioFile->good()){ // this loop is just to know how may rows are in the file
    getline (*ioFile, row); 
    i++;
  }

  content = new string[i]; // I allocate memory dynamically so that the numbers of   
  ioFile->seekg(0);        // pointer is the same as the number of rows   
  i = 0;

  while(ioFile->good()){
    getline (*ioFile, *content[i]);  //this is the tricky part
    i++;
  }
  ioFile->close();
}

あなたが私に提供できる助けやヒントを事前にありがとう! :-)

4

3 に答える 3

1

あなたのものが機能しない理由:

getline (*ioFile, *content[i]);  //this is the tricky part
                 ^^^
// You have an extra dereference above

次のようにする必要があります。

getline (*ioFile, content[i]);

どのように行うべきか:

std::ifstream f(filename);
std::vector<std::string> lines;
for(std::string temp; std::getline(f, temp); lines.push_back(std::move(temp)));

注: ここではクリーンアップは必要ありません。ifstream はそれ自体を閉じます。ベクターは割り当てたものを削除します。これは、ファイルの行を文字列として取得するためのはるかに小さく効率的なコードです。

于 2013-06-15T01:12:51.937 に答える