比较字符串 (C++)
Comparing Strings (C++)
我正在尝试获取文件中每个单词在单独文件中出现的次数。以下代码应使用 fl 中的单词生成 sl 中每个单词的出现次数,但它会输出 0 每个单词,即使有很多实例。我正在尝试找出问题所在,并且可以寻求帮助。 getNextWord() 函数只是 returns 文件中的下一个单词。
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() 位于单独的 class:
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 中的每个单词后 seek
sl 到开头的方法。
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 中的每个单词。
这将更正您实施的逻辑。然而,这并不是说它是推荐的 "best" 实现(以避免纯粹主义者对我大喊大叫 :P )。
我正在尝试获取文件中每个单词在单独文件中出现的次数。以下代码应使用 fl 中的单词生成 sl 中每个单词的出现次数,但它会输出 0 每个单词,即使有很多实例。我正在尝试找出问题所在,并且可以寻求帮助。 getNextWord() 函数只是 returns 文件中的下一个单词。
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() 位于单独的 class:
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 中的每个单词后 seek
sl 到开头的方法。
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 中的每个单词。
这将更正您实施的逻辑。然而,这并不是说它是推荐的 "best" 实现(以避免纯粹主义者对我大喊大叫 :P )。