Reputation: 71
I want to know why strcasecmp() is returning 0 the first time I use it but not the second.
In this example i'm specifically entering "hello world" into standard input. Instead of printing 0 0 it's printing 0 10. I have the following code.
#include "stdio.h"
#include "string.h"
int main(void) {
char input[1000];
char *a;
fgets(input, 1000, stdin);
a = strtok(input, " ");
printf("%d\n",strcasecmp(a,"hello")); //returns 0
a = strtok(NULL, " ");
printf("%d\n",strcasecmp(a,"world")); //returns 10
return 0;
}
What am I doing wrong?
Upvotes: 3
Views: 516
Reputation: 7482
The newline, you have entered after hello world
is part of the world
token because you use space as token separator.
If you use strtok(input, " \n");
instead of strtok(input, " ");
the program will behave correctly. In fact, you probably want to use tabulator as token separator as well.
The whole program will be:
#include "stdio.h"
#include "string.h"
int main(void) {
char input[1000];
char *a;
fgets(input, 1000, stdin);
a = strtok(input, " \n\t");
if (a == NULL) return(-1);
printf("%d\n",strcasecmp(a,"hello"));
a = strtok(NULL, " \n\t");
if (a == NULL) return(-1);
printf("%d\n",strcasecmp(a,"world"));
return 0;
}
Upvotes: 6