New to c++. I'm trying to figure out how to use strcmp with array's . I need to see if a array holds the word "hello". I can't get my code to work quite right. What is it missing?

using namespace std;

int main()
{       char a[30];
        char b[10];
        char word1[30];
        char word2[10];

                cout<< " enter in a phrase"<< endl;
                cin>> a;
                cout << "enter word you want to search for"<< endl;
                cin >> b;


                if (strcmp(word1,word2))
                cout<< "I found your word:"<< endl;

                cout << " that word was not found:"<<endl;

        return 0;
5 Years
Discussion Span
Last Post by deceptikon

strcmp() returns a comparison, not equality. If the result is 0, the two strings match. If the result is less than 0 the first string is lexicographically smaller, and if the result is greater than 0 the first string is lexicographically larger. So your test should look like this:

if (strcmp(word1,word2) == 0)

However, strcmp() compares strings in totality. If you want to search for a substring, you want strstr() instead:

if (strstr(word1, word2))

strstr() returns a null pointer if the second argument is not found within the first, so you can use an implicit failure check in the if statement. If you want to be explicit, you can do this:

if (strstr(word1, word2) != NULL)

We are only allowed to use the cstring functions in my class. I'm just not understanding how you can tell if a array holds a certain word such as "hello" or a phrase like "hello world".


We are only allowed to use the cstring functions in my class.

It's convenient that strstr() is in that library, isn't it? :rolleyes:


I wasn't aware of that. Like I said new to c++. Strstr isn't in the book we have.I will give that a try

Edited by Melly3


I wasn't aware of that.

Which means you didn't read the reference link in my initial reply. Sometimes I wonder why I even bother.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.