2014-02-27 47 views
0

我使用ifstream從文件中獲取行並將它們存儲爲字符串。每行包含一個沒有空格的單詞。從文件中讀取行 - 刪除多餘的空格

virtual void readFromFile(char* input){ 
     ifstream inf(input); 

     if(!inf){ 
      cerr << "The specified file could not be found." << endl; 
     } 

     while(inf){ 
      string str; 
      getline(inf, str); 
      pushFront(str); // store it in my data structure 

     } 

     inf.close(); 
    } 

file.txt的

a <= returns length 1 (correct) 
at <= returns length 3 
ate <= returns length 4 
rate <= returns length 5 
irate <= returns length 6 

當我打電話length()上對應的第一個文件的字符串,它返回正確的值。但是,在對應所有其他行的字符串上調用length將導致+1的偏移量。例如,如果字符串的長度實際上是5,則返回6.這是否與新行有關?如果是這樣,我怎樣才能從文件中正確提取這些單詞?

+0

你確定沒有間隔寫在線上?這可能與Linux系統用於新行'\ r'和'\ n'的兩個符號有關,但我認爲getline將會修剪它們兩者。即便如此,請嘗試查看不正確的單詞是以'\ r'還是'\ n'結尾,我們肯定知道。 –

+0

讓我檢查一下。 – Bob

+0

對我來說很好嗎? http://oi61.tinypic.com/99qqsz.jpg – Bob

回答

1

您正在使用vi作爲文本編輯器,因此您可以通過執行:set list來顯示不可見字符。這將幫助你找出你在大多數線條上看到的這些附加字符。

在linux中,通常的行結尾是「\ r \ n」,它實際上是兩個字符。我不確定getline是否會忽略它們。但是,以防萬一,你可以添加以下邏輯:

getline(inf, str); 
int len = str.size(); 
if (str[len - 1] == '\r') { 
    str.pop_back(); // not C++11 you do it str = str.erase(str.end() - 1); 
} 
pushFront(str); // store it in my data structure 
+1

我認爲它會很好鏈接到一些[關於getline函數的參考](http://en.cppreference.com/w/cpp/string/basic_string/getline)或[類似的討論](http://stackoverflow.com/questions/ 6089231 /獲取-STD-ifstream的對手柄-LF-CR-和CRLF/6089413#6089413)。 – mbschenkel

0

如果你的文本文件中的格式定義,即每行只包含一個字,所以它更容易和更請務必閱讀本字。

void readFromFile(char* input){ 
    ifstream inf(input); 
    if(!inf){ 
     cerr << "The specified file could not be found." << endl; 
    } 
    for(string word; inf >> word;) 
     pushFront(word); // store it in my data structure 
} // inf.close() is done automaticly leaving the scope 
相關問題