views:

305

answers:

5

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  A: 

Does buf contain a trailing newline?

rjh
+5  A: 
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.

N 1.1
Thanks, that works! I think the problem was the way I was initializing buf, there must've been some extra characters on the end of what I was trying to compare.
hora
+1  A: 

Have you tried

printf("num: %d\n", strcasecmp(buf, "h"));
Michael Dean
I have, yes, in this case it returns 10...
hora
+2  A: 

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

Justin Ethier
I don't know about the `read` function (which I don't think is even available on Windows), but text mode streams will have newlines converted automatically.
jamesdlin
+2  A: 

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"));
}
Derek Ledbetter