0

我正在实现一个功能,用户可以在其中搜索向量中的单词。唯一的问题是,我的搜索功能只能找到某些单词,我不知道为什么。

 ifstream in("testdata.txt");
string word1;
vector<string> individual_words;
while (in >> word1)
{
    individual_words.push_back(word1);
}

文件 testdata.txt 里面是:

Hello how are you
Good are you well?
Snazzy piece of toast

这是我比较这两个词的代码。

string search_word;

 while (cin >> search_word)
    {

        for (int f=0; f < individual_words.size(); f ++)
        {
            cout << "individual words: " << individual_words[f] <<endl;
            cout << "search word: " << search_word;
            if (search_word == individual_words[f])
            {
                cout << " FOUND THE SAME WORD\n!";
                break;
            }


        }
}

出于某种原因,它只捕获 .txt 文件中的某些单词,我不确定为什么。我看过它,它似乎忽略了第一个单词,并且忽略了每个句子的最后一个单词。

4

1 回答 1

0

您的向量将有重复项,因此它只会在循环中断之前找到单词“are”和“you”的第一次出现。从逻辑上讲,这部分代码没有其他错误,但最好写成:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main() 
{
    // simplified for demonstration purposes
    string test = "Hello how are you\nGood are you well?\nSnazzy piece of toast";
    istringstream iss(test);
    vector<string> words;
    copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(words));

    string search_word;
    while (cin >> search_word)
    {
        // this works, but is unnecessary
        /*for (int f=0; f < words.size(); f ++)
        {
            cout << "individual words: " << words[f] <<endl;
            cout << "search word: " << search_word;
            if (search_word == words[f])
            {
                cout << " FOUND THE SAME WORD\n!";
                break;
            }
        }*/

        // this is a better approach
        vector<string>::iterator it = find(words.begin(), words.end(), search_word);
        if (it != words.end())
        {
            cout << "Found the word:  " << *it << endl;
        }
        else
        {
            cout << "Not found!" << endl;
        }
    }
    return 0;
}
于 2013-10-14T00:14:09.870 回答