2013-03-29 28 views
1

我做了一個類叫做FileReader。這是我閱讀這門課的功能。它打開一個文件並讀取它。當然,它將文件的內容放入我的課程的一個名爲「內容」的變量中。它在最後一行。字符串有一個' n'太多

std::string file_content; 
std::string temp; 
std::ifstream file; 

file.open(filepath,std::ios_base::in); 

while(!file.eof()){ 

    temp.clear(); 
    getline(file, temp); 

    file_content += temp; 
    file_content += '\n'; 
} 

file_content = file_content.substr(0, file_content.length()-1); //Removes the last new line 

file.close(); 

content = file_content; 

的文件,我打開具有以下內容:

「你好\ nWhat氏達\ nCool」。

當然,我並沒有在我的文本文件中精確地編寫\ n。但正如你所看到的,最後沒有新的路線。

我的問題是,「內容」,每當我打印到屏幕上,在最後一個新行。但我刪除了最後一個新行......出了什麼問題?

+0

你是行結尾\ r \ n還是\ n? – bizzehdee

+0

如果你使用'Windows',行分隔符總是'\ r \ n',而Unix只使用'\ n' ... –

+0

我正在使用Linux –

回答

6

經典錯誤,在讀取之前使用eof而不是之後。這是正確的

while (getline(file, temp)) 
{ 
    file_content += temp; 
    file_content += '\n'; 
} 

,或者如果你必須使用eof,切記不要前使用getline

for (;;) 
{ 
    getline(file, temp); 
    if (file.eof()) // eof after getline 
     break; 
    file_content += temp; 
    file_content += '\n'; 
} 

這是令人難以置信有多少人認爲eof可以預測下一個讀是否有一個EOF問題。但事實並非如此,它會告訴你最後一次讀取有一個eof問題。在C和C++的整個歷史中一直如此,但它顯然是違反直覺的,因爲許多人犯這個錯誤。

+0

謝謝。有效! –

4

eof不會被設置,直到您嘗試讀過去文件結束。你的循環迭代四行三行;不過,最後一次迭代沒有讀取數據。

更正確的方法是將您的while循環更改爲while (std::getline(file, temp));這將在第三次讀取後到達文件末尾時終止循環。

相關問題