std::getline 读取最后一个字符串两次

std::getline read the last string twice

本文关键字:两次 字符串 getline 读取 最后一个 std      更新时间:2023-10-16

测试文件写成

Sat Aug 10 22:03:09 2019
Test completed

首先我使用了 in.eof((,但有人告诉我永远不要使用 thoes in.eof((。

enter code here
#include <fstream>
#include <iostream>
#include <string>
int main() {
//test.txt is a test file. 
std::ifstream in("test.txt");
if (!in.is_open()) {
std::cout << "file not found" << std::endl;
return 0;
}
std::string s;
while (in) {
getline(in, s);
std::cout << s << std::endl;
}
return 0;
}

我希望结果像

Sat Aug 10 22:03:09 2019
Test completed

但结果是

Sat Aug 10 22:03:09 2019
Test completed
Test completed

问题出在代码的这一部分,就在最后一次成功读取之后:

while (in) {          // succeeds
std::getline(in, s);   // fails (EOF), and s is unchanged

这完全等同于为什么 iostream::eof 在循环条件中(即while (!stream.eof())( 被认为是错误的?

解决方法是使getline()结果成为条件的一部分:

while(std::getline(in, s)) {

做你想做的事的标准方法是

for (std::string s; std::getline(in, s);)

该问题可能与文件末尾的新行符号 (n( 有关。

getline成功时循环,而不是在istream有效时循环。

while (getline(in, s)) {
std::cout << s << std::endl;
}