如何计算文本文件中特定单词的出现次数?

How do I count the number of occurrences of a specific word in a text file

本文关键字:单词 何计算 计算 文件 文本      更新时间:2023-10-16

我被我正在做的一项任务难住了,甚至不知道从哪里开始,我想我所拥有的可能完全没用。

我正试图读取一个包含8行文本的文本文件,每个文本中都有"行"这个词。我需要计算单词"line"在文件中出现的总次数。

到目前为止我写的

代码

ifstream file("output.txt");    
int wcount = 0;
string token;
string word(line);
while (file>>token)
    if (word == token)
    wcount++;
cout << wcount << endl;

我已经看了几个小时了,寻找了每一个可能的解决方案,但什么也没找到。请帮助。

改变这一行:

string word(line);

string word("line");

检查文件是否成功打开…

ifstream file("output.txt");
if ( !file )
{
   // Deal with error.
}
// Read the contents of the file.

检查单词是否被正确读取…

while (file>>token)
{
    std::cout << "Read the token: `" << token << "'" << std::endl;
    if (word == token)
       wcount++;
}