2013-02-11 36 views
0

我不能爲了我的生活找出爲什麼這不起作用。我不得不對文件中的單詞列表進行頻率檢查,並且在讀取它們時,我試圖檢查當前單詞是否與字符串數組中的元素相對應,並確保它們在我之前不等於添加它。代碼如下:檢查從文件讀入數組中的字符串

fin.open(finFile, fstream::in); 

if(fin.is_open()) { 
    int wordArrSize; 
    while(!fin.eof()) { 
     char buffer[49]; //Max number chars of any given word in the file 
     wordArrSize = words.length(); 

     fin >> buffer; 

     if(wordArrSize == 0) words.push_back(buffer); 

     for(int i = 0; i < wordArrSize; i++) { //Check the read-in word against the array 
      if(strcmp(words.at(i), buffer) != 0) { //If not equal, add to array 
       words.push_back(buffer); 
       break; 
      } 
     } 



     totNumWords++; //Keeps track of the total number of words in the file 
    } 
    fin.close(); 

這是一個學校項目。我們不允許使用任何容器類,所以我構建了一個結構來處理擴展char **數組,推回和彈出元素等。

+2

@Alex,爲什麼地球上不應該問作業問題? – SingerOfTheFall 2013-02-11 07:25:49

+0

@SingerOfTheFall我認爲他們被禁止? – 2013-02-11 07:36:11

+1

@Alex,不,我們只是不再用[tag:作業]標記問題。作業問題與其他任何問題沒有區別。你可以在[tag:homework]標籤info – SingerOfTheFall 2013-02-11 07:40:02

回答

1
for(int i = 0; i < wordArrSize; i++) { //this part is just fine 
    if(strcmp(words.at(i), buffer) != 0) { //here lies the problem 
     words.push_back(buffer); 
     break; 
    } 
} 

你將進入你的if聲明每次當前字不匹配數組中的第i個字。所以,大多數時候,這將是您進入循環的第一次迭代。這意味着在循環開始時(在字符串列表中與緩衝區不匹配的第一個單詞),您將緩衝區添加到字符串列表並打破循環。

你應該做的是完成檢查整個words數組,然後將緩衝區添加到數組中。所以你應該有這樣的事情:

bool bufferIsInTheArray = false;//assume that the buffered word is not in the array. 
for(int i = 0; i < wordArrSize; i++) { 
    if(strcmp(words.at(i), buffer) == 0) { 
     //if we found a MATCH, we set the flag to true 
     //and break the cycle (because since we found a match already 
     //there is no point to continue checking) 
     bufferIsInTheArray = true; 
     break; 
    } 
//if the flag is false here, that means we did not find a match in the array, and 
//should add the buffer to it. 
if(bufferIsInTheArray == false) 
    words.push_back(buffer); 
} 
+0

這樣做了,謝謝!我不知道爲什麼這件事早些時候沒有提到。看起來像我的邏輯起初是充分證明的 – 2013-02-11 07:53:25

1

我認爲您的代碼words.push_back(buffer);應該超出for循環。 將一個標誌來檢查,如果你發現在for循環數組緩衝區,並根據標誌其添加到陣列外的for循環

+0

試過了,沒有去。 這與strcmp()取得兩個char *無關?除非我錯過了某些東西,否則緩衝區[49]在傳遞時應該衰減爲指針。真的沒有其他的解釋...這個檢查應該被切斷和乾燥argh – 2013-02-11 07:35:59

+0

你確定。我修改的意思是在上面的答案中正確編碼你是否嘗試過這個答案。在你的代碼中,如果任何一個單詞與單詞中的單詞不同,那麼它會添加到數組中 – 999k 2013-02-11 07:43:08

+0

@TaylorBishop它確實會衰減到一個指針。 – 2013-02-11 07:44:45