I am a C newbie and learning string tokenizing. I am trying to compare two strings in the following way. But the string comparison I am doing is failing.
Can you please let me know what I am missing here?
I couldn't find another similar question, may be due to my inexperience in C. If one exists, can you please redirect me to it?
char* input = "comparer here";
char* args[5];
int counter = 0;
char *tok = strtok(input, " ");
while (tok != NULL) {
args[counter] = tok;
counter ++;
if (counter == 5)
break;
tok = strtok(NULL, " ");
}
char* comp_str = "comparer";
if (strcmp(args[0], comp_str) == 1) {
// do some stuff
}
It fails because
strcmp
(and its siblings) returns a zero value if they are equal, a negative value if the first is less than the second, and a positive value if the first is greater than the second.The negative or positive value is not specified. In most implementations it is the difference of the first different characters. But that is not guaranteed.
Comparing the result to 1 is very unlikely to succeed.