Why is my strcmp() failing?

834 views Asked by At

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
}
3

There are 3 answers

0
wallyk On BEST ANSWER

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.

2
donjuedo On

You are defining a string called input, but using a variable called message, undefined.

0
Shayne Kelly II On

strcmp() returns 0 when the two strings to be compared are equal. You should change 1 to 0 if you are trying to check if the two strings are equal.