strcasecmp in C returns 156 instead of 0, any idea

2019-07-15 08:46发布

问题:

I have the following code:

printf("num: %d\n", strcasecmp(buf, "h\n"));

And I get the following results when I try plugging in different letters:

a: -7
g: -1
i: 1
j: 2
h: 156
H: 156

Should strcasecmp not return 0 when buf is equal to H or h? Any ideas why it's returning 156? I need to figure out how to check whether the user types H or h.

Thanks!

Edit: I'm reading buf in the following way: read(0, buf, MAXBUFLEN);

回答1:

printf("num: %d\n", strcasecmp(buf, "h"));

Why \n at the end, if you want to compare with h or H ?


main(){
 char *s = "hH";
 printf("%d\n", strcasecmp(s, "Hh"));
}

0


read() also stores whitespace. So, if you are using read, compare with "h\n".

main(){
 char *buf = malloc(sizeof(char)*10);
 read(0, buf, 10);
 printf("%s %d %d\n", buf, strcasecmp(buf, "h\n"), strcasecmp(buf, "h"));
}

h
h
  0 10

I entered h in the above case.

Also, use strncasecmp if you want to compare a fixed number of characters.



回答2:

Try comparing it to "h\r\n" - if you are on windows, both \r and \n will end a line.



回答3:

read does not put a zero at the end. It just deals with arrays of bytes, and knows nothing about null-terminated strings. So do like this:

char buf[MAXBUFLEN+1];
int readResult = read(0, buf, MAXBUFLEN);
if(readResult < 0)
{
    // handle error
}
else
{
    buf[readResult] = 0;
    printf("num: %d\n", strcasecmp(buf, "h\n"));
}


回答4:

Does buf contain a trailing newline?



回答5:

Have you tried

printf("num: %d\n", strcasecmp(buf, "h"));


标签: c string strcmp