[英]Strange getline behavior in c++
我有以下文件:
BB
7.501106 5.324115
7.997006 8.287983
11.314904 11.768281
...
而且我100%確信文件沒有問題,甚至在vim中用:set list
顯示換行符:
BB$
7.501106 5.324115$
7.997006 8.287983$
11.314904 11.768281$
...
但是,當我打開並在第一行中閱讀時,會發生一些奇怪的事情。 我有以下代碼:
std::ifstream file(filename);
std::string line;
if (!file.is_open()) {
std::cerr << "parseConfig: Error opening config file: " << filename << std::endl;
exit(1);
}
getline(file, line);
std::cout << "line is: <" << line << ">" << std::endl;
if (line.compare("BB")) {
std::cerr << "parseConfig: Error in config file, first line is not BB" << std::endl;
exit(1);
}
現在我知道文件正在正確打開,因為我們一直到最終錯誤。
打印輸出如下:
>ine is: <BB //What!!!?? Why did this happen?
parseConfig: Error in config file, first line is not BB
這讓我感到很奇怪,好像在文本文件中有回車符一樣。 但是我非常確定沒有。
有任何想法嗎?
看起來該文件處於DOS模式。 檢查vim是否在底部顯示[dos]
或檢查file yourfile.txt
。
另一種檢查方法是通過cat -A
(如果您的cat沒有-A
則通過cat -v
傳遞文件或程序的輸出。 回車費將顯示為^M
要轉換為UNIX格式,請在vim中執行:set ff=unix
,然后保存文件。 或者,如果有,請使用dos2unix
命令行工具。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.