[英]Comparing Strings (C++)
我試圖獲取在單獨文件中每個單詞的文件中出現的次數。 以下代碼應該使用fl中的單詞來生成sl中每個單詞的出現次數,但是,即使有很多實例,它也為每個單詞輸出0 。 我正在嘗試找出問題所在,並且可以通過一些幫助來解決。 getNextWord()函數僅返回文件中的下一個單詞。
while(fl.isWord()){
int total = 0;
string temp1= fl.getNextWord();
while(sl.isWord()){
string temp2 = sl.getNextWord();
if(temp1.compare(temp2)!=0) total ++;
//if(temp1 == temp2) total++;
}
cout << temp1 << " " << total << endl;
}
函數isWords()在單獨的類中:
bool ReadWords::isWord(){
if(file.good())
return !eoffound;
else
return eoffound;
示例清單:
fl內容肯德基奶牛
sl內容:該死的牛牛雞蘋果蘋果肯德基食品肥牛
輸出:
肯德基0
牛0
輸出應為:
肯德基1
牛3
編輯部分:
string ReadWords::getNextWord(){
file >> theWord;
return theWord;
}
假設您解析文件的功能正確,則實現邏輯存在問題。 問題是,從fl獲得第一個單詞后,您將搜索整個文件sl,該文件達到其eof,然后以后的搜索將不起作用,因為sl位於eof。
您需要的是一種方法,在您完成fl中的每個單詞之后,將sl seek
到其開頭。
while(fl.isWord()){
/* seek sl to beginning; then do the rest */
int total = 0;
string temp1= fl.getNextWord();
while(sl.isWord()){
string temp2 = sl.getNextWord();
if(temp1 == temp2) total++;
}
cout << temp1 << " " << total << endl;
}
編輯:如果您找不到一種查找文件的方法,請使用vector<string>
一次將其所有單詞加載到內存中,然后對fl中的每個單詞在此矢量上進行搜索。
這將糾正您的實現邏輯 。 但是,這並不是說這是推薦的“最佳”實現(以避免純粹主義者對我大喊:P)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.