2010-01-05 82 views
1

我正在嘗試編寫一個函數,它讀取txt文件中的各行並將它們存儲在字符串數組中。除了讀取空白行時,該函數可以正常工作。例如:C++流不讀取空行

功能

ifstream flinput("somefile.txt") 
string line; 

while(getline(flinput, line)) { 
    //Add line to array 

所以問題是,如果文本文件看起來像這樣。

Line1 Some Text blar blar blar 
\n 
Line3 Some Text blar blar blar 
\n 
Line5 Some Text blar blar blar 

該數組最終看起來像這樣。

array[0] = "Line1 Some Text blar blar blar" 
array[1] = "Line3 Some Text blar blar blar" 
array[2] = "Line5 Some Text blar blar blar" 

當它看起來像這樣。

array[0] = "Line1 Some Text blar blar blar" 
array[1] = "" 
array[2] = "Line3 Some Text blar blar blar" 
array[3] = "" 
array[4] = "Line5 Some Text blar blar blar" 

我在做什麼錯?

由於

回答

3

從函數getline文檔...

如果找到定界符,則提取並丟棄,即,它不被存儲和之後的下一個輸入操作將開始。如果你不想要這個角色被提取,你可以使用member get代替。

所以你的代碼正在做它應該做的。如果要保存\ n,您必須使用Get手動解析事件,如文檔所示。

+0

更簡單的方法可以是將到陣列之前檢查一個空字符串。如果字符串爲空,則向數組追加一個「\ n」字符串。 – 2010-01-05 18:01:30

0

您的代碼適用於Linux系統上的gcc 4.3.2。我認爲它應該。

0

這將是簡單的使用一個迭代,here's一個例子: