my problem is how to use if else statement with the use of character type string (char str[40]) for exemple
char str[30];
cin>>str; or gets(str) or getline(str,30)
if(str=="hello") cout<<"world";
i search this everywhere but every answer could not satisfied me.

What you are talking about is a c string or array of char.

You need to loop through the char array checking each given char against its test char.

basic example.

char * given = "given";
char * test = "given";

int i = 0;
while (test[i]){
    if (test[i] != given[i])
        return bad;

return good;

In this case, when you do this:


on the left you have a pointer, and on the right you have a pointer. The value of a pointer is the number it holds; a single memory address. So the value on the left would be something like 0x0324FEED (a single number, representing an address) and the value on the right would be something like 0x03284EEA (a single number, representing an address). Those numbers (two memory addresses) are what is being compared.

So you are testing to see if both pointers are pointing at the same memory. Of course, they are not pointing at the same memory.

What you are trying to do is compare not the pointers, but what they are pointing at.

You could do this yourself (for example, with something like:

if( str[0] == 'h' && str [1] == 'e' && str[2] == 'l' && str [3] == 'l' && str[4] == 'o')

which compares the characters one at a time, or you can use a standard library function named strcmp.

if (strcmp(str, "hello") == 0)
  // they are the same

Alternatively, and this is a FAR BETTER option, don't use char arrays. Use proper C++ strings.

std::string str;
cin >> str;
if (str == "hello")


For char arrays you can use strcmp() which is defined in string.h to check if the two character arrays are the same or not. strcmp() returns 0 if the two are identical.

if( strcmp(str,"hello") == 0) cout<<"world";

This question has already been answered. Start a new discussion instead.