2014-12-02 71 views
0

我正在嘗試編寫一個程序來檢查其他單詞中有多少單詞。然後告訴用戶哪個單詞中有最多的單詞。出於某種原因,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

回答

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.