我正在尝试编写一个程序来检查其他单词中有多少单词。然后告诉用户哪个单词中的单词最多。由于某种原因,while循环中断,我无法重新加载文件。有什么想法吗?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct finalWord {
string word;
int number;
};
ostream& operator<<(ostream& o, const finalWord& f) {
return o << f.word << ": " << f.number;
}
int main () {
finalWord f;
string line, holder, line2;
ifstream myFile("enable1.txt");
int counter;
int holdlen;
size_t found;
if (myFile.is_open()){
while(getline(myFile,line)){
holder = line;
while (getline(myFile, line)){
found = holder.find(line);
if (found != string::npos){
counter++;
}
if (counter > holdlen) {
f.word = line;
f.number = counter;
holdlen = counter;
}
counter = 0;
}
}
}
cout << f << endl;
}
答案 0 :(得分:0)
实际上你遇到的问题是因为你使用的两个循环 myFile
IN First WHILE loop it will take a word
IN Second WHILE loop it will go through the rest of the file.
在下列情况下,这将是一个问题。
If a String "I am Happy" is occurred more than once then it will iterate for each occurrence to search up to end of the file.
So to avoid that you need to take the unique strings in an vector as said by Vaughn Cato and then do a check for the occurrence of that string in the whole file to make it efficient.