2
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.

user2889150
  • 23
  • 1
  • 3

4 Answers4

5

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");
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • I just used your exact program and both of these changes fixed it fine. You must not be showing us something important. – Carl Norum Oct 17 '13 at 06:20
0

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

0

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

if(strcmp(tok, "*\n") == 0)
Thanushan
  • 532
  • 2
  • 8
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().