首页 > 解决方案 > C ++ - 程序检查向量中指定的单词

问题描述

我的程序应该将输入的单词与被删减的单词向量进行比较;任何应该被审查的单词都会打印“BLEEP”而不是单词。但是,我遇到的问题是,我的嵌套 for 循环是将输入的单词与向量中的第一个审查单词进行比较,然后显示一些内容,与第二个进行比较,显示等等,而不是将单词与整个向量,然后显示某些内容,然后继续输入下一个单词。我该如何解决这个循环?

int main()
{
    vector<string> censored = {"Rabbit", "Food", "Dog", "Monkey", "Zebra", "Kiwi"};         //Censored words

    cout << "Please enter words followed by a space. Ctrl+Z when you're done.\n";
    vector<string> words;
    for (string entry; cin >> entry;)                                   //Reads words separated by a space
        words.push_back(entry);                                                             //Puts words into vector words

    for (int w = 0; w < words.size(); w++) //Checks a word through censored vector before going to next word
        for (int c=0; c < censored.size(); c++)
            if (words[w] == censored[c])
                cout << "\nBLEEP";
            else
                cout << "\n" << words[w];

    keep_window_open();
}

标签: c++nested-loops

解决方案


您已经找到问题所在,并且可以执行它!

我遇到的问题是我的嵌套 for 循环正在将输入的单词与向量中的第一个审查单词进行比较,然后显示一些东西,与第二个比较,显示等等

正是这个程序,

for (int w = 0; w < words.size(); w++)        //  For each word
    for (int c=0; c < censored.size(); c++)   //  and each censored word
        if (words[w] == censored[c])          //  compare them ...
            cout << "\nBLEEP";
        else
            cout << "\n" << words[w];

目的是

在显示某些内容之前将单词与整个向量进行比较,然后继续输入下一个单词

因此代码可能会更改为

for (int w = 0; w < words.size(); w++)        //  For each word
{
    bool in_censored = false;                 //  we will find whether the world is in censored vector.
    for (int c=0; c < censored.size(); c++)   //  For each censored word
        if (words[w] == censored[c])          //  compare
            in_censored = true;               //  if same, the result for the word is set.
    if (in_censored)                          //  If the word is in censored.
        cout << "\nBLEEP";                    //  ...
    else
        cout << "\n" << words[w];
}

推荐阅读