【问题标题】:ifstream - Move to next wordifstream - 移动到下一个单词
【发布时间】:2015-09-15 22:54:02
【问题描述】:

我有点不清楚 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: 对不起,如果我在指导方针和规则方面做错了什么。这是我第一次发帖。

【问题讨论】:

    标签: c++ string ifstream word


    【解决方案1】:

    每次您使用>> 从流中提取时,它都会自动前进到下一项(这就是您的while 循环如何在文件中不断前进,直到找到“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;
    

    【讨论】:

    • 好的。我在想它在循环结束时推进了。谢谢。
    【解决方案2】:

    为了澄清 matt 的回答,在 istream 上使用 >> 将找到下一个不是空格的字符,然后读入它找到的所有字符,直到它到达空格字符或文件结尾。

    【讨论】:

      猜你喜欢
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      • 2023-01-22
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      相关资源
      最近更新 更多