2010-05-03 62 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 
}