同一段使用 `getline` 讀取文本行的代碼,在 Visual Studio (MSVC) 與 g++ 下行為不同:
導致同一邏輯在 g++ 下多出一個換行符,造成後續處理(如 `substr(1)` 去除前導空格)錯誤。
C++ 標準(ISO/IEC 14882)規定 `std::getline`:
Extracts characters until `delim` (default `\n`) is found. The delimiter is extracted but not appended to the string.
因此 **MSVC 行為符合標準**,g++ (libstdc++) 在某些版本/平台下保留 `\n` 屬於庫實現差異(或與底層 C 語言 `fgets` 行為一致)。
string line;
while (getline(cin, line)) {
if (!line.empty() && line.back() == '\n') line.pop_back(); // 移除可能的 \n
if (!line.empty() && line.back() == '\r') line.pop_back(); // 處理 Windows \r\n
// 繼續處理 line
}
// test_getline.cpp
#include
#include
#include
using namespace std;
int main() {
ifstream in("test.txt"); // 內容:Hello\nWorld\n
string s;
getline(in, s);
cout << "len=" << s.length() << " content=[" << s << "]\n";
return 0;
}
編譯運行: