简体   繁体   English

比较字符串(C ++)

[英]Comparing Strings (C++)

I am trying to get the amount of occurrences in a file of each word in a separate file. 我试图获取在单独文件中每个单词的文件中出现的次数。 The following code should produce the number of occurrences of each word in sl using the words in fl but instead, it outputs 0 for each words even when there are many instances. 以下代码应该使用fl中的单词来生成sl中每个单词的出现次数,但是,即使有很多实例,它也为每个单词输出0 I'm trying to figure out what the problem is and could do with some help. 我正在尝试找出问题所在,并且可以通过一些帮助来解决。 The getNextWord() function simply returns the next word in the file. 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;
}

The function isWords() is in a separate class: 函数isWords()在单独的类中:

bool ReadWords::isWord(){
    if(file.good())
        return !eoffound;
    else
        return eoffound;

Exemplar lists: 示例清单:

fl content kfc cows fl内容肯德基奶牛

sl content: damn cows cows chicken apples apples kfc food fat cows sl内容:该死的牛牛鸡苹果苹果肯德基食品肥牛

output: 输出:

kfc 0 肯德基0

cows 0 牛0

output should be: 输出应为:

kfc 1 肯德基1

cows 3 牛3

edited part: 编辑部分:

string ReadWords::getNextWord(){
    file >> theWord;
    return theWord;
}

Assuming your functions for parsing the files are correct, there is a problem in the logic of the implementation. 假设您解析文件的功能正确,则实现逻辑存在问题。 The problem is that after you get the first word from fl, you search the whole file sl, this one reaches its eof, then later searches will not work because sl is at eof. 问题是,从fl获得第一个单词后,您将搜索整个文件sl,该文件达到其eof,然后以后的搜索将不起作用,因为sl位于eof。

What you need is a way to seek sl to its beginning after you finish with each word from fl. 您需要的是一种方法,在您完成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;
}

EDIT: if you cannot find a way to seek the file, load all of its words into memory using vector<string> , in one pass, then do the search on this vector for each word from fl. 编辑:如果您找不到一种查找文件的方法,请使用vector<string>一次将其所有单词加载到内存中,然后对fl中的每个单词在此矢量上进行搜索。

This will correct the logic of your implementation. 这将纠正您的实现逻辑 HOWEVER, this is NOT to say that it is the recommended and "best" implementation (to avoid purists shouting at me :P ). 但是,这并不是说这是推荐的“最佳”实现(以避免纯粹主义者对我大喊:P)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM