0

Consider the following code for tokenizing the string at space characters,

int main()
{
    char L[100];
    fgets(L, 100, stdin);

    for(char* token = strtok(L, " "); token != NULL; token = strtok(NULL, " ")){
        char L1[10];
        strcpy(L1, token);

        printf("%s", L1);
    }
}

When the input is given as,

60@2 120@3

It eventually prints out as expected,

60@2120@3

Now, I would like to tokenize the string again that contains "@" character, Say, I wanna tokenize 60@2 and 120@3 with "@" character.

So, I started with the following code,

int main()
{
    char L[100];
    fgets(L, 100, stdin);

    for(char* token = strtok(L, " "); token != NULL; token = strtok(NULL, " ")){
        char L1[10];
        strcpy(L1, token);

        printf("%s", L1);

        char* token2 = strtok(L1, "@"); // extra line 1
        printf("%s", token2);           // extra line 2
    }
}

However for the same input,

60@2 120@3

The output generated was,

60@26022

Can you explain what is happening in the second case?

Sathyamoorthy R
  • 383
  • 4
  • 19
  • 2
    Nested uses of strtok do not work. Use strtok_r on POSIX or strtok_s on Windows instead. The inner strtok screws up the outer. There are other questions which cover this; it is a duplicate – Jonathan Leffler Jul 02 '17 at 03:13
  • however, I copy the token inside the for() loop to another variable so that the original remains intact. – Sathyamoorthy R Jul 02 '17 at 03:15
  • You can't copy the hidden state. That hidden state is is exposed in the interface to the alternatives. – Jonathan Leffler Jul 02 '17 at 03:17
  • Strtok is broken for exactly this reason. You cannot call `strtok` in a nested fashion yourself; you cannot call any other function that might possibly call `strtok` either: https://stackoverflow.com/questions/28588170/is-strtok-broken-or-just-tricky – abelenky Jul 02 '17 at 03:19

0 Answers0