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

时间:2014-05-05 01:16:32

标签: c++ string io count

我被一项我正在努力的任务所困扰,甚至不知道从哪里开始,我认为我所拥有的任务可能完全没用。

我试图阅读包含8行文字的文字文件,每行文字都包含" line"在某个地方。我需要计算单词" line"的总次数。出现在文件中。

我到目前为止的代码

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

cout << wcount << endl;

我已经看了好几个小时,并寻找所有可能的解决方案并且没有任何结果。请帮忙。

1 个答案:

答案 0 :(得分:4)

更改此行:

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++;
}
相关问题