计算特定单词在c++文本文件中出现的次数
Counting how many times certain words show up in a text file in C++
我正试图用两个不同的文本文件制作一个程序。其中一个包含我要分析的实际文本,另一个包含单词列表。程序应该检查列表中的单词何时出现在文本中并计数。以下是我到目前为止的(不工作的)代码:
#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包含
这是一段文字。它将被加载到一个程序中。
和list.txt包含
会
预期结果为3。然而,无论文本文件中有什么,程序总是给我答案0。我已经检查了程序实际上是通过计算循环次数来读取文件的,并且它工作了。
Thanks in advance
在我看来,你总是只比较第一个文件的第一个字母和整个第二个文件,你做:
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);
}
程序只遍历"目标单词列表"(即data2
)文件一次。文件流是"单向的":一旦耗尽,就需要倒带,否则它将留在最后。内循环
while ( data2 >> word2 )
...
将只执行第一次,即data1
的第一个字。对于第二个和随后的所有单词,data2
将已经在文件的末尾,因此代码甚至不会进入循环。
你应该在内存中读取目标单词,并在内循环中使用该列表。更好的是,将单词放在set<string>
中,并使用该集合进行计数。
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何使用 c++ 实现并发文件/文本编辑?
- 我需要转换一些代码,以便它适用于输入和输出文件文本
- 通过套接字发送二进制文件.文本文件有效,其他文件无效
- 将大型数据文件拆分为多个小文件(文本格式)
- 如何读取输入文件(文本文件)并将输入验证为有效整数
- 从文本文件/文本流中读取Q字符串错误
- 从文本文件(文本解析器)C++中读取行和列的逻辑
- 如何将*.css文件(文本文件)的内容与附加信息存储在新文件中?
- 关于内存映射文件和使用大文件文本编辑器
- 如何在读取文件文本时跳过"n"
- 使用libzip从.zip获取文件(文本除外)