计算单词在C ++文件中出现的次数

时间:2020-04-30 04:44:55

标签: c++ file

我正在尝试搜索文件中的单词,每次出现时它都会使计数增加1。 该文件当前有多行,其中带有单词Culture。程序每次运行都会输出1。

int main()
{
  fstream plate("data.txt", ios::in | ios::out | ios::app);
  int count = 0;
  string search = "Culture";
  string temp;
  while(!plate.eof())
    {
      getline(plate, temp);
      if(temp == search)
        {count++;}
    }

  cout << count << endl;    

  return 0;
}

我不明白为什么每次只能输出1

2 个答案:

答案 0 :(得分:1)

您正在逐行读取文件,比较整行而不是单个单词,仅计算从每行开头到结尾与search字符串完全匹配的行。

尝试以下方法:

int main() {
    ifstream plate("data.txt");
    int count = 0;
    string search = "Culture";
    string temp;
    while (plate >> temp) {
        if (temp == search) {
            ++count;
        }
    }
    cout << count << endl;
    return 0;
}

答案 1 :(得分:0)

问题是,您正在将整行与键进行比较,因此只要整行等于单词,计数器就会增加。 而是尝试检查行中是否包含单词。

if (temp.find(search) != std::string::npos) {
    // contains the word
    count++;
}

更新: 如果该单词可能在每行中出现多次,那么您需要考虑使用另一个循环:

int step = search.size();
int position = 0;

while((position = temp.find(search, position)) != std::string::npos) {
    position += step;
    count++;
}