c++ - 计算某些单词在 C++ 中的文本文件中出现的次数

标签 c++ string file-io

我正在尝试用两个不同的文本文件制作一个程序。其中一个包含我要分析的实际文本,另一个包含单词列表。该程序应该检查列表中的单词何时出现在文本中并对其进行计数。这是我到目前为止的(非工作)代码:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main () {

    string word1;
    string word2;
    int listHits = 0;

    ifstream data1 ("text.txt");
    if ( ! data1 ) {
    cout << "could not open file: " << "text.txt" << endl;
        exit ( EXIT_FAILURE );
  }

    ifstream data2 ("list.txt");
    if ( ! data2 ) {
    cout << "could not open file: " << "list.txt" << endl;
        exit ( EXIT_FAILURE );
  }

    while ( data1 >> word1 ) {
        while ( data2 >> word2 ) {
            if ( word1 == word2 ) {
                listHits++;
            }
        }
    }

    cout << "Your text had " << listHits << " words from the list " << endl;

    system("pause");

    return 0;
}

如果text.txt包含

Here is a text. It will be loaded into a program.

和list.txt包含

will a

预期的结果是 3。但是,无论文本文件中的内容是什么,程序总是给我答案 0。我已经检查过该程序通过计算它执行循环的次数来实际设法读取文件, 并且有效。

提前致谢

最佳答案

在我看来,你总是只比较第一个文件的第一个字母和整个第二个文件,你这样做:

  while ( data1 >> word1 ) {
        while ( data2 >> word2 ) { // <---- after this ends the first time, it will never enter again
            if ( word1 == word2 ) {
                listHits++;
            }
        }

您需要在第二个循环完成后“重置”data2,以便它再次从文件开头读取:

 while ( data1 >> word1 ) {
        while ( data2 >> word2 ) {
            if ( word1 == word2 ) {
                listHits++;
            }    
        }
        data2.seekg (0, data2.beg);
   }

关于c++ - 计算某些单词在 C++ 中的文本文件中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15829178/

相关文章:

javascript - 如何在jquery中获取最终粘贴的文本?

string - 打印 Int(或 Int 到 String)

android - 文件创建时没有写入任何数据

java - Java 中的文件读取,具有相同的文件读取器

c++ - Windows 服务与 NamedPipe 之间的访问安全

c++ - 确定不安全转换的警告 clang

c++ - `resize`减少 vector 容量会有风险吗?

c++ - Windows 对音量 slider 使用什么对数函数?

c++ - 查找 blob 中最长的 blob 前缀

c# - 指向本地目录的 UNC 路径比本地访问慢得多