ifstream - 移动到下一个单词

ifstream - Move to next word

我有点不清楚 ifstream 是如何工作的。我已经搜索过了,但找不到这个问题的具体答案。

我想做的是停在某个词上,然后对后面的词做一些事情。

具体来说,我的程序会查找包含单词的文件。每次它看到字符串 "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;

如何告诉 ifstream 转到下一个单词?

P.S:如果我在指导方针和规则方面做错了什么,我深表歉意。这是我第一次发帖。

每次您使用 >> 从流中提取时,它会自动前进到下一个项目(这就是您的 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 上使用 >> 将找到下一个不是 space 的字符,然后读入它找到的所有字符,直到它到达 space 字符或文件结尾。