2010-05-03 69 views
1

好吧,它已經有一段時間我做了任何文件輸入或字符串操作,但我正在試圖做的是如下C++字符串和文件輸入

while(infile >> word) { 
    for(int i = 0; i < word.length(); i++) { 
     if(word[i] == '\n') { 
      cout << "Found a new line" << endl; 
      lineNumber++; 
     } 
     if(!isalpha(word[i])) { 
      word.erase(i); 
     } 
     if(islower(word[i])) 
      word[i] = toupper(word[i]); 


    } 
    } 

現在我認爲這是不工作因爲>>跳過新行字符?如果是這樣,最好的辦法是做到這一點。

回答

1

如何使用getline()

string line; 
while(getline(infile, line)) 
{ 
    //Parse each line into individual words and do whatever you're going to do with them. 
} 
9

我猜wordstd::string。當使用>>時,第一個空格字符終止「單詞」,下一次調用將跳過空格,因此word中不會出現空白區域。

你不會說你實際上想要做什麼,但對於基於行的輸入,你應該考慮使用自由函數std::getline,然後將每行分割爲單獨的單詞。

E.g.

std::string line; 
while(std::getline(std::cin, line)) 
{ 
    // parse line 
}