【发布时间】:2018-01-18 11:43:10
【问题描述】:
我在逐行读取文件时注意到一些奇怪的行为。如果文件以\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;
}
当我测试它 (http://cpp.sh/72dgw) 时,我得到了这些输出:
(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" ""
所以最后一个\n 被跳过(6)、(7)和(8),很好。但是为什么不是(4)和(5)呢?
这种行为背后的原因是什么?
【问题讨论】: