-1
#include<stdio.h>

int main(){

char name[20];

scanf(" %s", name);

if (name == 'James'){

    printf("Welcome James");
}else{

    printf("You are not James");
}

}

Hope you got my idea. I know this doesn't work. But is there any way to do something like this?

SirDarknight
  • 83
  • 1
  • 2
  • 11

3 Answers3

3

Use

if (strcmp(name, "James") == 0)

instead of

if (name == 'James')

Man page of strcmp:

Return Value

The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

msc
  • 33,420
  • 29
  • 119
  • 214
  • It's worth noting that `==` compares string pointers, not strings, so it compiles but is generally not what people want. – tadman Nov 07 '17 at 05:57
2

try: strcmp()

#include<stdio.h>

int main(){

char name[20];

scanf(" %s", name);

if (strcmp(name,"James")){

    printf("Welcome James");
}else{

    printf("You are not James");
}

}

Ref : How do I properly compare strings?

Alden Ken
  • 142
  • 8
0

In C you have to use cmp string function:

strcmp(const char* s1, const char* s2);

Return values of function:

return value == 0 - s1 is equals s2
return value > 0 - s1 is longer than s2
return value < 0- s1 is smaller than s2

It is beacuse if you write:

char name_buff[20];
if (name_buff == "James")
{
...

It doesn't mean comparsion of strings but of address in memory. So you have to use strcmp().

Adam
  • 114
  • 3