How does std::getline decides to skip last empty line?

Viewed 684

I noticed some strange behaviour when reading a file by line. If the file ends with \n (empty line), it may be skipped...but not always, and I don't see what makes it be skipped or not.

I wrote this little function splitting a string into lines to reproduce the issue easily:

std::vector<std::string> SplitLines( const std::string& inputStr )
{
    std::vector<std::string> lines;

    std::stringstream str;
    str << inputStr;

    std::string sContent;
    while ( std::getline( str, sContent ) )
    {
        lines.push_back( sContent );
    }

    return lines;
}

When I test it (http://cpp.sh/72dgw), I get those outputs:

(1) "a\nb"       was splitted to 2 line(s):"a" "b" 
(2) "a"          was splitted to 1 line(s):"a" 
(3) ""           was splitted to 0 line(s):
(4) "\n"         was splitted to 1 line(s):"" 
(5) "\n\n"       was splitted to 2 line(s):"" "" 
(6) "\nb\n"      was splitted to 2 line(s):"" "b" 
(7) "a\nb\n"     was splitted to 2 line(s):"a" "b" 
(8) "a\nb\n\n"   was splitted to 3 line(s):"a" "b" ""

So last \n is skipped for case (6), (7) and (8), fine. But why it's not for (4) and (5) then?

What's the rational behind this behaviour?

1 Answers
Related