-
strstr problem...
Okay, I have to do some mini-review for my programming class, but I haven't touched C++ in ~6months or so, so I'm a bit rusty.
I have to have the user input text, then reject it if it contains profanity.
this is what I have so far, but I can't seem to get it to work. As you can see, I have the words it's checking for in a seperate file so it's easy to update.
Code:
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
char str[100];
string prof1, prof2, prof3, prof4, prof5;
int main()
{
ifstream fin;
fin.open("profanity.txt");
char *pdest;
int result;
fin >> prof1 >> prof2 >> prof3 >> prof4 >> prof5;
string words[5] = {prof1, prof2, prof3, prof4, prof5};
cout << "Enter text: ";
cin >> str;
for(int a=1; a<5; a++)
{
pdest = strstr( str, words[a] );
if ( pdest != NULL )
{
cout << "Profanity found!";
return 0;
}
else
cout << "No profanity found\n";
}
return 0;
}
any help would be appreciated. I can't figure this out, it should be pretty easy, and it's driving me nuts!
-
Use the std::string class not character arrays. They're better and they contain their own substr() method which is significantly easier to work with.
Now for some fundamental problems with your code:
You're mixing your headers up... <stdio.h> and <string.h> aren't under the standard namespace and are both deprecated (actually they aren't standard C++, at all). You should be using <cstring> for the latter and the former has no reason to be there, at all. It's not being used (it's counterpart is <cstdio> however).
You're also declaring string objects which aren't defined in <string.h>, they're defined in <string>. You likely lucked out because one of your other libraries includes <string>.
Your closing brace is missing on your for loop.
You have an unnecessary return in your if statement.
...and this is just bickering, but I would be explicitly closing my ifstream before returning.
-
> for(int a=1; a<5; a++)
Arrays also start at 0
-
>> I can't seem to get it to work.
What is the problem? A compile error? It always outputs not found? What input are you giving it?
>> Your closing brace is missing on your for loop.
I don't think so, the else closing brace is actually for the for loop (the else has no opening brace). Better indentation and more consistent bracing would make it a lot easier to see.
>> actually they aren't standard C++, at all
Yes, they are standard. They are just deprecated. They must work on all standards-conformant compilers despite the fact that the C++ versions are preferred.
>> I would be explicitly closing my ifstream before returning.
I wouldn't. But I wouldn't quibble either way.