c++ - 从特定填充读取到 C++ 中的最后一行

标签 c++ ifstream eof seekg

我有一个包含很多行的文本文件。我想将每一行存储在一个字符串 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/

相关文章:

C++ : How to skip first whitespace while using getline() with ifstream object to read a line from a file?

c++ - fstream包含ofstream和ifstream的所有内容?

c - 为什么我需要按两次 Ctrl-D 来标记文件结束?

c - 将 scanf 输入拆分为数组,直到 EOF

c++ - 学习半条命 2 SDK 有哪些好的方法?

c++ - 在保存之前转换值的自定义迭代器

C++按 block 读取文本文件

c - 如何正确使用scanf和EOF?

c++ - 更改OpenCV卡尔曼滤波器的增益以使其响应更快

c++ - 使用c++ packaged_task构建生产者消费者模式