Filtering out bad words in MUD Game

204 views Asked by At

In my C++ MUD game i want to be able to eliminate the player from being able to enter curse words. You all know what they are, no need for examples. So i tried something like this:

vector<string> vulger = { "You know what goes in here");

void Player::SendString(const std::string& p_string)
    {
for (vector<string>::iterator it = vulger.begin(); it != vulger.end(); ++it)
    {
        if (!p_string.compare(*it) || !p_string.find(*it))
        {
            //Testing what words are been neglected by the if statement.
            //cout << *it;
                Conn()->Protocol().SendString(*Conn(), p_string + newline);
        }
    }

    }

But all this does is loop through strings that are sent to the network. Including announcments.

Can anyone see what im doing wrong or suggest anything maybe ?

2

There are 2 answers

7
Thomas Matthews On BEST ANSWER

Change the || in your if statement to &&:

    void Player::SendString(const std::string& p_string)
    {
      for (vector<string>::iterator it = vulger.begin(); it != vulger.end(); ++it)
      {
#if 0
// Original:
        if (!p_name.compare(*it) && !p_name.find(*it))
        {
          Conn()->Protocol().SendString(*Conn(), p_string + newline);
        }
        else
        {
          cout << "Vulgar word found: " << *it << "\n";
        }
#else
// Edit 1:  Changed ordering.
        if ((p_name == *it) || (p_name.find(*it) != std::string::npos))
        {
          cout << "Vulgar word found: " << *it << "\n";
        }
        else
        {
          Conn()->Protocol().SendString(*Conn(), p_string + newline);
        }
#endif

      }
    }
0
Adrian McCarthy On

You are treating the return value of std::string::find as a bool, when, in actuality, it returns an offset into the string with a special magic value of npos if it's not found.

if (my_string.find("foo") == std::npos) {
   // foo is NOT in my_string
} else {
   // foo is in my_string
}