What I am trying to do is compare the contents of array s to the string name (for a filter) but it just continues and prints whatever goes through. I think the problem is with my if statement but I have tried everything that I thought was valid code.

#include <iostream>
#include <string>
using namespace std;

void check(string name)
{
string s[4];
s[0]=="badword1";
s[1]=="badword2";
s[2]=="badword3";
s[3]=="badword4";
if(name==s[0-4])
{
string name="******";
}
}

string name;


int main()
{
int x;
x=0;
for(x=0; x<1;)
{
cout<<"hello whats your name: ";
getline(cin,name);
check(name);
cout<<name;
cout<<endl;
}

if(name==s[0-4]) says to compare name to s[-4], which is way out of the array's bounds.

You will have to construct a loop and compare name to each string in array s, one at a time.

if(name==s[0-4])   <-------??
{
    string name="******";
}

Creative syntax? How about a for loop:

for (int i = 0;i<4;i++)
{
     if(name == s[i])
           name = "**********";
}

if you pass in name by reference you will get the change otherwise how is your new name going to change in main()

for(x=0; x<1;)

You're essentially running through this loop once. Why even have it?

EDIT: vmanes reigns supreme on this one

Edited 6 Years Ago by jonsca: n/a

EDIT2: would that code work?

if(name==s[0]||s[1]||s[2]||s[3])
{
string name="******";
cout<<name;
}

Thanks guys :)
EDIT: jonsca i actually just ran through your idea in my head and what you suggested means it would have to run throught the loop multiple times to see if it was equal to whatever was stored in the array. also i could have swore i saw someone compare the entire arrays data to a single variable. vmanes your idea is what i thought of first write the entire thing out but i though there would be a simpler way to do it using arrays. :(

Edited 6 Years Ago by Anarionist: n/a

s[0]=="badword1";
s[1]=="badword2";
s[2]=="badword3";
s[3]=="badword4";

These four lines will do absolutely nothing. You need to be careful to differentiate between the assignment and equivalent operators.

EDIT2: would that code work?

if(name==s[0]||s[1]||s[2]||s[3])
{
string name="******";
cout<<name;
}

You aren't thinking about what is happening here. The if statement is not going to do anything meaningful. C++ operator precedence says that == is evaluated before ||. So, you first test if name is equal to s[0]. You get a boolean value from this, say 1. Then you use a logical or ( || ) to compare the boolean value to a string. This is not going to help you out. I think you meant name==s[0]||name==s[1]||name==s[2]||name==s[3]

This article has been dead for over six months. Start a new discussion instead.