我有一个包含很多行的文本文件。我想将每一行存储在一个字符串 vector 中。我想从文件中读取直到到达最后一行。我使用了 EOF 函数,但它似乎也在最后一行之后存储了空行。这是我的代码片段。 text_list 是一个 vector ,其中存储了文件的所有行。
void TextBuddy::storeDataFromFileInVector(string filename){
ifstream infile;
int numbers;
string textMessage;
infile.open(filename);
while (!infile.eof()){
getline(infile, textMessage);
text_list.push_back(textMessage);
}
infile.close();
}
最佳答案
eof() 不展望 future 。因此,当您刚好在 EOF 之前时,您会将它也读入您的 vector 并可能损坏它。
将所有行读入 vector 的更好方法是:
string line;
while(getline(inFile, line)
text_list.push_back(line);
一旦您读取了 EOF 或发生任何其他错误,您的循环就会中断。
另一种方法是使用迭代器和算法库:
copy(istream_iterator<string>(inFile), istream_iterator<string>(),
back_inserter(text_list));
这取决于你喜欢哪一个。
关于c++ - 从特定填充读取到 C++ 中的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18516028/