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?

#include<iostream>
#include<cctype>
#include<cstring>
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;

                strcpy(word1,a);
                strcpy(word2,b);

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

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



        return 0;
}

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.