HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Filtering out rude words

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
rudewordsoutfiltering

Problem

This program will filter the input by replacing matching bad words with "Bleep!". I'd like the code to be more concise and C++ style where possible. One thing that bugs me is the was_bad flag I think is needed to skip printing a word that has matched one of my bad words - if there was some better way to skip the rest of the while loop upon encountering a bad word so I don't print Bleep! poop, for instance.

#include 
#include 
#include 

using namespace std;

int main(void) 
{
    int i, was_bad = false;
    string input, bad[] = {"poop", "balls"};
    vector  badwords(bad, bad + sizeof(bad) / sizeof(string));

    while (cin >> input)
    {
        for (i = 0; i < badwords.size(); ++i)
            if (badwords[i] == input)
            {
                cout << "Bleep! ";
                was_bad = true;
                break;
            }

        if (!was_bad)
            cout << input << " ";

        was_bad = false;
    }

    return 0;
}


One thing that did strike me was to use a ternary operator:

while (cin >> input)
{
    for (i = 0; i < badwords.size(); ++i)
        if (badwords[i] == input)
        {
            is_bad = true;
            break;
        }

    cout << (is_bad ? "Bleep! " : input + " ");

    is_bad = false;
}

Solution

Instead of iterating over a vector I'd use std::find().
Even better, instead of std::vector I'd use std::set:

#include 
#include 
#include 

using namespace std;

int main(int argc, const char * argv[])
{
    string bad[] = {"poop", "balls"};
    set bad_words(bad, bad + sizeof(bad) / sizeof(string));

    string input;
    while(cin >> input)
    {
        if(bad_words.find(input)!=bad_words.end()){
            cout << "bleep! ";
        }
        else {
            cout << input << " ";
        }
    }
}

Code Snippets

#include <iostream>
#include <set>
#include <string>

using namespace std;

int main(int argc, const char * argv[])
{
    string bad[] = {"poop", "balls"};
    set<string> bad_words(bad, bad + sizeof(bad) / sizeof(string));

    string input;
    while(cin >> input)
    {
        if(bad_words.find(input)!=bad_words.end()){
            cout << "bleep! ";
        }
        else {
            cout << input << " ";
        }
    }
}

Context

StackExchange Code Review Q#18673, answer score: 6

Revisions (0)

No revisions yet.