#include<stdio.h>
int main(void)
{
char name[40];
scanf("%s",name);
if(name == "yes")
{
printf("%s",name);
}
return 0
}

- 12,700
- 3
- 19
- 44

- 1
- 2
-
search for string comparison issues, – Sourav Ghosh Nov 01 '18 at 14:43
-
1You are comparing pointers, not strings. – Matthieu Brucher Nov 01 '18 at 14:44
-
thank you so much can i ask why if(name=="yes") is not avalible? – RIPCpp Nov 01 '18 at 14:57
2 Answers
You need to use strcmp
for string comparison.
Replace
if(name == "yes")
With
if(strcmp(name,"yes") == 0)
strcmp
returns
0 if both strings are identical (equal)
Negative value if the ASCII value of first unmatched character is less than second.
Positive value if the ASCII value of first unmatched character is greater than second.

- 12,700
- 3
- 19
- 44
-
-
1@richbak: It has to do with how C treats array expressions - under most circumstances, an expression of array type "decays" to a pointer, so what you wind up comparing are the *addresses* of the strings, not their contents. There is a reason for this behavior, but it's more than will fit into a comment. – John Bode Nov 01 '18 at 14:58
==
isn't defined for string (or any other array) comparisons - you need to use the standard library function strcmp
to compare strings:
if ( strcmp( name, "yes" ) == 0 )
or
if ( !strcmp( name, "yes") )
strcmp
is a little non-intuitive in that it returns 0 if the string contents are equal, so the sense of the test will feel wrong. It will return a negative value if the first string is lexicographically less than the second, and a positive value if the first string is lexicographically greater than the second.
You'll need to #include <string.h>
in order to use strcmp
.
For comparing arrays that aren't strings, use memcmp
.

- 119,563
- 19
- 122
- 198