Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

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

When using std::getline to read lines from a file, I need it to pick up each blank line at the end of the file.


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

getline() is always skipping the last blank line of a file and not adding it to the lines vector. I need the final blank line to be included IF it's in the file. How do I do this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...