繁体   English   中英

我想编写一个 c++ 程序,其中有一个文件,我想看看文件中出现了多少次“好”这个词。 为什么这不起作用

[英]I want to write a c++ program in which I have a file and I want to see how many times the word "good" appears in the file. Why does this not work

所以这就是我尝试做的。 这也是我主要用来做单词搜索代码的逻辑。 我基本上是在看我是否能找到字符“g”,然后我看看是否有与 good 匹配的字母。 如果它们匹配,那么我会 count++ 来计算它,最后我输出我的结果:-



#include<iostream> //headers
#include<fstream>

using namespace std;

int main()
{
    
    char arr[10000];
    //declaration
    fstream fileis;
    
    fileis.open("fileis.txt",ios::in);
    
    while (!fileis.eof( ))      
     {     //reading loop
             
          fileis>>arr;
          cout<<arr<<endl;  
     }
     
    int count=0;
    
     for(int i=0; arr[i] != '\0'; i++)  //main loop
     {
        if(arr[i] == 'g' && arr[i+1] == 'o' && arr[i+2] == 'o' && arr[i+3] == 'd') //condition to check if the word is there
        {
                count++;     
        }
    }
        
    fileis.close();
    
    cout<<"The word good appeared "<<count<<" times."<<endl;
    
    return 0;
    
}

这是我的建议:

std::string word;
count = 0;
//...
while (fileis >> word)
{
  // Convert word to all lower case for easy comparison.
  std::transform(word.begin(), word.end(), word.begin(), tolower);

  if (word == "good") ++count;
}

上面的代码片段有一些问题供 OP 查找(例如在“good”之后读入标点符号时会发生什么)。

默认情况下,从流中读取字符串会读取“单词”,空格分隔。

暂无
暂无

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

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