2013-04-28 77 views
0

我正在讀取文件中的單詞,輸出應該是該單詞出現的單詞和行號。我的代碼運行良好,但我遇到了問題我存儲每個單詞的行號的向量。在向量中添加字符串數字時出錯

例如,文本文件:

I am for truth 
no matter who tells it, 
I am for justice, 
no matter who it is for or against 
Malcom X 

輸出我得到:

I 13 
am 1133 
for 111333444444 
truth 1111 
no 24 
matter 2244 
who 222444 
tells 2222 
it 222224444 
justice 3333 
is 44444 
or 4444444 
against 44444444 
Malcom 5 
X 55 

和輸出我期待:

against 4 
matter 2, 4 
am 1, 3 
no 2, 4 
for 1, 3, 4 
or 4 
I 1, 3 
tells 2 
is 4 
truth 1 
it 2, 4 
who 2,4 
justice 3 
X 5 
Malcolm 5 

這裏是我的代碼:

int main(int argc, char *argv[]) { 

    fstream infile ; 
    BSTFCI <string>* bst = new BSTFCI<string>(); 
    string word; 
    string line; 
    vector <string>words; 
    vector <string>line_no; 
    int count = 0; 
    infile.open("test.txt" , ios::in); 
    if(infile.fail()) 
    { 
     cout<<"Error Opening file"<<endl; 
     return 0; 
    } 

    while(getline(infile , line)) 
    { 
     ++count; 
     istringstream buffer(line); 
     ostringstream counter; 
     while (buffer >> word) 
     { 

      for(int i=0 ; i<word.size();i++) { 
       if(ispunct(word[i])) 
       word.erase(i,1);   
      } 

      if(!bst->search(word)) { 
       bst->insert(word); 
       words.push_back(word); 
       counter << count; 
       line_no.push_back(counter.str()); 
      } else { 
       counter<<count; 
       for(int k=0;k<words.size();k++) { 
        if(word==words.at(k)) 
         line_no.at(k)+=counter.str(); 
       } 
      } 

     } 
    } 

    for(int i=0;i<words.size();i++) 
     cout << words.at(i) << " " << line_no.at(i) << endl; 

    infile.close(); 
    return 0; 

} 
+0

請改善您的縮進。 – Rubens 2013-04-28 17:43:47

+0

如果有效,請告訴我 – smttsp 2013-04-28 17:54:31

回答

2

嘗試刪除counter<<count。它在我看來是錯誤的原因。如果它不工作刪除count++;

+0

是啊!非常感謝 – SUE 2013-04-28 17:53:58

+0

哪一個工作? – smttsp 2013-04-28 17:54:48