0

I am trying to parse spaces and then commas for a project the data is similar to this:

37,4 23,4,9,6 22,11 99,29

I want to first split them with spaces and then split the commas to get individual numbers. But this doesn't work.

char *token = strtok(singleLine, " ");

while( token != NULL ) {
    token = strtok(NULL, " ");
    char *token2 = strtok(token, ",");
    while(*token2 != NULL){
        printf("%s", token)
        token2 = strtok(NULL,",");
    }
}

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Vehbi
  • 53
  • 3

2 Answers2

1

The strtok function uses an internal static variable to keep track of its state, so if you attempt to interleave processing of two different strings / substrings the internal state gets corrupted.

If your system supports it, you should instead use strtok_r (or strok_s on Windows) This function takes an additional parameter to keep track of its current state.

char *state_inner, *state_outer;
char *token = strtok_r(singleLine, " ", &state_outer);

while (token != NULL ) {
    token = strtok_r(NULL, " ", &state_outer);
    char *token2 = strtok_r(token, ",", &state_inner);
    while (token2 != NULL){
        printf("%s", token);
        token2 = strtok_r(NULL,",", &state_inner);
    }
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
dbush
  • 205,898
  • 23
  • 218
  • 273
  • I have to compile and run the project on some school zeus VPN thing. I will check if I can use strtok_r, when I use in on my local it gives me that implicit function declaration error. – Vehbi Oct 23 '20 at 19:51
  • @Vehbi `strtok_r` should be available on Linux. If you're using MSVC (i.e. Windows) the equivalent function is `strtok_s`. – dbush Oct 23 '20 at 19:54
0

You can't "nest" calls to strtok like that - you'll have split into the string "37,4 23,4,9,6 22,11 99,29" into the sequence "37,4", "23,4,9,6", "22,11", "99,29" and then split each of those tokens to get the individual numbers.

John Bode
  • 119,563
  • 19
  • 122
  • 198