如何使 std::getline() 包含最后一个空行?

How to make std::getline() include last empty line?

当使用 std::getline 从文件中读取行时,我需要它来拾取文件末尾的每个空行。


    //add each line to lines
    while (std::getline(file, line))
        lines.push_back(line);

getline() 总是跳过文件的最后一个空白行,而不是将其添加到行向量中。如果它在文件中,我需要包含最后的空行。我该怎么做?

我认为这是 by design:

Extracts characters from input and appends them to str until one of the following occurs (checked in the order listed).

a) end-of-file condition on input, in which case, getline sets eofbit.
...

If no characters were extracted for whatever reason (not even the discarded delimiter), getline sets failbit and returns.

failbit 将导致流的 bool 转换运算符为 return false,从而中断循环。

因此,我认为您需要做的是循环检查每次成功读取时是否设置了 eofbit。如果设置,最后一行由 EOF 而不是换行符终止,因此不会有后续行可读。如果不设置,不管是否为空,都会多一行读取。

while (std::getline(file, line)) {
    lines.push_back(line);
    if (file.eof()) break;
}
if (file.eof() && file.fail()) {
    lines.push_back(“”);
}

Demo