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.

Recommended Answers

All 4 Replies

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:

if(str=="hello")

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")
{

}

thanks to allllllllllllllllllllllllllllll

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";

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.