我有一个指向字符串类的指针数组,我需要将文件中的一行复制到每个指针中,但是我不确定该怎么做。
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();
}
在此先感谢您提供的任何帮助或提示! :-)
最佳答案
为什么你的不起作用:
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关闭自身。向量将删除其分配的内容。这是更小的高效代码,用于将文件的行作为字符串。