strcasecmp in C returns 156 instead of 0, any ideas why?

一笑奈何 提交于 2019-12-11 03:04:40

问题


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


来源:https://stackoverflow.com/questions/2512591/strcasecmp-in-c-returns-156-instead-of-0-any-ideas-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!