检查自己的文件

问题描述:

我正在尝试编写一个程序来检查其他单词中有多少单词。然后告诉用户哪个单词中有最多的单词。出于某种原因,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; 
} 
+1

您可能想要先将所有单词读入到'std :: vector'中,以便您可以轻松地使用它们。 – 2014-12-02 06:08:29

+0

谢谢。我正在考虑这样做,但不确定是否有办法在没有将整个列表加载到内存中的情况下执行此操作。 – Jlegend 2014-12-02 06:30:40

+0

@Jiegend:这是可能的,但您需要每次重新打开文件。 – 2014-12-02 06:36:58

其实你所面对的问题,是因为两个循环使用的是具有相同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.