C++ std::getline如何决定跳过最后一个空行?

C++ std::getline如何决定跳过最后一个空行?,c++,string,getline,eol,C++,String,Getline,Eol,我在逐行阅读文件时注意到一些奇怪的行为。如果文件以\n(空行)结尾,它可能会被跳过…但并不总是如此,我不知道是什么原因导致它被跳过或不被跳过 我编写了这个小函数,将一个字符串拆分成几行,以便轻松地重现问题: std::vector<std::string> SplitLines( const std::string& inputStr ) { std::vector<std::string> lines; std::stringstream st

我在逐行阅读文件时注意到一些奇怪的行为。如果文件以
\n
(空行)结尾,它可能会被跳过…但并不总是如此,我不知道是什么原因导致它被跳过或不被跳过

我编写了这个小函数,将一个字符串拆分成几行,以便轻松地重现问题:

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;
}
因此,对于情况(6)、(7)和(8),跳过最后一个
\n
,可以。但是为什么不适合(4)和(5)呢


这种行为背后的理性是什么?

有一篇有趣的帖子很快提到了这种“奇怪”的行为:

正如前面提到的,
\n
是一个终止符(这就是为什么它的名称是行的结尾),而不是一个分隔符,这意味着行被定义为“以'\n'结尾”,而不是“以'\n'分隔”

我不清楚这是如何回答这个问题的,但事实上确实如此。按如下所述重新配制,它变得像水一样清澈:

如果您的内容计算了“\n”的出现次数
x
,那么您将得到
x
行,或者
x+1
如果文件末尾有一些额外的非“\n”字符。

(1) "a\nb"       splitted to 2 line(s):"a" "b"    (1 EOL + extra characters = 2 lines)
(2) "a"          splitted to 1 line(s):"a"        (0 EOL + extra characters = 1 line)
(3) ""           splitted to 0 line(s):           (0 EOL + no extra characters = 0 line)
(4) "\n"         splitted to 1 line(s):""         (1 EOL + no extra characters = 1 line) 
(5) "\n\n"       splitted to 2 line(s):"" ""      (2 EOL + no extra characters = 2 lines)
(6) "\nb\n"      splitted to 2 line(s):"" "b"     (2 EOL + no extra characters = 2 lines)
(7) "a\nb\n"     splitted to 2 line(s):"a" "b"    (2 EOL + no extra characters = 2 lines)
(8) "a\nb\n\n"   splitted to 3 line(s):"a" "b" "" (3 EOL + no extra characters = 3 lines)
(1) "a\nb"       splitted to 2 line(s):"a" "b"    (1 EOL + extra characters = 2 lines)
(2) "a"          splitted to 1 line(s):"a"        (0 EOL + extra characters = 1 line)
(3) ""           splitted to 0 line(s):           (0 EOL + no extra characters = 0 line)
(4) "\n"         splitted to 1 line(s):""         (1 EOL + no extra characters = 1 line) 
(5) "\n\n"       splitted to 2 line(s):"" ""      (2 EOL + no extra characters = 2 lines)
(6) "\nb\n"      splitted to 2 line(s):"" "b"     (2 EOL + no extra characters = 2 lines)
(7) "a\nb\n"     splitted to 2 line(s):"a" "b"    (2 EOL + no extra characters = 2 lines)
(8) "a\nb\n\n"   splitted to 3 line(s):"a" "b" "" (3 EOL + no extra characters = 3 lines)