简体   繁体   English

ifstream-移至下一个单词

[英]ifstream - Move to next word

I am a little bit unclear as to how ifstream functions. 对于ifstream的功能,我还不清楚。 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" 每次看到字符串“ NEWWORD”时,都需要对“ 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? 如何告诉ifstream转到下一个单词?

PS: Sorry if I did anything wrong as far as guidelines and rules. PS:对不起,如果我在准则和规则方面做错了什么。 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": 每次使用>>从流中提取内容时,它都会自动前进到下一项(这是while循环不断在文件中前进直到找到“ NEWWORD”的方式。您可以在看到“ 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上使用>>将找到下一个非空格字符,然后读取找到的所有字符,直到到达空格字符或文件末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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