I think this is 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.
That failbit
will cause the stream’s bool
conversion operator to return false, breaking the loop.
So, what I think you will have to do is make your loop check if eofbit
is set on each successful read. If set, the last line was terminated by EOF and not by a line break, so there won’t be a subsequent line to read. If not set, there will be another line to read, whether it is blank or not.
while (std::getline(file, line)) {
lines.push_back(line);
if (file.eof()) break;
}
if (file.eof() && file.fail()) {
lines.push_back(“”);
}
Demo
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…