prgrmmr
prgrmmr

Reputation: 189

Why is my strcmp() failing?

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
}

Upvotes: 0

Views: 873

Answers (3)

Shayne Kelly II
Shayne Kelly II

Reputation: 143

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.

Upvotes: 0

wallyk
wallyk

Reputation: 57774

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.

Upvotes: 3

donjuedo
donjuedo

Reputation: 2505

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

Upvotes: 0

Related Questions