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