开发者

c++ strings and file input

Ok, its been a while since I've done any file input or string manipulation but what I'm attempting to do is as follows

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


    } 
   } 

Now I assume this is not working because >> skips the new line character?? If so, whats a better way to do this.


I'll guess that word is a std::string. When using >>, the first white-space character terminates the 'word' and the next invocation will skip white-space so no white-space while occur in word.

You don't say what you're actually trying to do but for line based input you should consider using the free function std::getline and then splitting each line into words as a separate step.

E.g.

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


There is getline function.


How about using getline()?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜