1
當我逐行讀取文件時,我注意到了一些奇怪的行爲。如果文件以\n
(空行)結尾,則可能會跳過...但並非總是如此,我不明白是什麼讓它跳過或不跳過。std :: getline如何決定跳過最後一個空行?
我寫了這個小功能,將字符串分割線重現輕鬆的問題:
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)呢?
這種行爲背後的理由是什麼?