Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...