user2889150
user2889150

Reputation: 23

trouble with strcmp() in C

char* mystr = calloc(25, sizeof(char));
fgets(mystr, 25, stdin); // I enter "6 7 *" in here, without the quotes

char* tok;
tok = strtok(mystr, " ");
while (tok != NULL) {
    if(strcmp(tok, "*") == 0)
        //It never meets this condition, but I don't understand why
    else
        //do something else here
    tok = strtok(NULL, " ");
}

The problem is that the strcmp(tok, "*") never returns as being equal, even though tok reads in the asterisk from the original string. I don't understand why it never meets this condition.

Upvotes: 2

Views: 3403

Answers (4)

Pallavi Gk
Pallavi Gk

Reputation: 1

Another input for you. strtok() is not thread safe. Be careful while using. If you are having multiple threads(both calling strtok() for some purpose), use strtok_r().

Upvotes: 0

Thanushan
Thanushan

Reputation: 532

The strcmp() compare two strings. You have to provide * as a string with the terminating character "*\n".

if(strcmp(tok, "*\n") == 0)

Upvotes: 0

user2889221
user2889221

Reputation: 1

Because fgets is embedding the newline character into the variable mystr. This is throwing off the comparison. Try to remove "\n" from variable.

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 224854

Your * token is likely also containing the \n character you typed to complete your input. Either compare a single character with one of:

  if(tok[0] == '*')

  if(strncmp(tok, "*", 1) == 0)

or add \n to your separator list:

  tok = strtok(NULL, " \n");

Upvotes: 5

Related Questions