سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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

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

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

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().

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top