简体   繁体   中英

ifstream - Move to next word

I am a little bit unclear as to how ifstream functions. I have searched, but can't find a specific answer to this question.

What I am trying to do is stop at a certain word, but then do something with the word after that.

Specifically, my program looks through a file containing words. Each time it sees the string "NEWWORD" it needs to do something with the word following "NEWWORD"

string str;
ifstream file;
file.open("wordFile.txt");
while(file >> str){
   //Look through the file
   if(str == "NEWWORD"){
        //Do something with the word following NEWWORD
   }

}     
file.close;

How can I tell ifstream to go to the next word?

PS: Sorry if I did anything wrong as far as guidelines and rules. This is my first time posting.

Each time you extract from a stream using >> it automatically advances to the next item (that is how your while loop keeps advancing through the file until it finds "NEWWORD". You can just extract the next item when you see "NEWWORD":

string str;
ifstream file;
file.open("wordFile.txt");
while(file >> str){
   //Look through the file
   if(str == "NEWWORD"){
        //Do something with the word following NEWWORD
        if (file >> str) {
             // the word following NEWWORD is now in str
        }
   }

}     
file.close;

为了阐明Matt的答案,在istream上使用>>将找到下一个非空格字符,然后读取找到的所有字符,直到到达空格字符或文件末尾。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM