Search code examples
cstrtokstrcmp

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.


Solution

  • 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");