Trying to split into two delimiters and it won't work - C

I wrote below code to read line by line from stdin ex.

city=Boston;city=New York;city=Chicago\n

and then split each line by ';' separator and print of each record. Then, in another loop, I try to split the record into the delimiter '=' to get to the actual values. But for some reason, the main (first) loop does not go beyond the first iteration, why?

char*   del1 = ";";
char*   del2 = "=";
char    input[BUFLEN];

while(fgets(input, BUFLEN, fp)) {

        input[strlen(input)-1]='\0';
        char* record = strtok(input, &del1);

        while(record) {
                printf("Record: %s\n",record);

                char*  field = strtok(record, &del2);
                while(field) {
                     printf("Field: %s\n",field);
                     field = strtok(NULL, &del2);
                }

                record = strtok(NULL, &del1);
        }
}
+3
source share
4 answers

Two things: firstly, this line is not very good:

 input[strlen(input)-1]='\0';

fgets () always ends with '\ 0', and this will give strange results when your input is not completed exactly in '\ n'.

-, strtok() . strtok_r(), char ** .

+3

, strtok, strtok_r, , strtok , . record = strtok (NULL), .

+2

strtok, strtok .

;, , = .

char*   del1 = ";";
char*   del2 = "=";
char    input[BUFLEN];
char*   tokens[255]; // have to be careful not to go more then that
while(fgets(input, BUFLEN, fp)) {

    // input[strlen(input)-1]='\0'; // you don't need that fgets add the NULL
    char* record = strtok(input, del1);
    i = 0;
    while(record) {

            tokens[i++] = strdup(record);  
            record = strtok(NULL, del1);
    }
    for(v = 0; v < i; v++){
      char*  field = strtok(token[v], del2);
      while(field) {
          printf("Record: %s\n",token[v]);
          printf("Field: %s\n",field);
          field = strtok(NULL, del2);
      }
    }
}

, strdup free strdup .

, , strtok

char * strtok ( char * str, const char * delimiters );

&del, del char *.

+1

:

  • : a=1;b=2;c=3\n
  • fgets: a=1;b=2;c=3\0
  • 1- strtok (-NULL,...): a=1\0b=2;c=3\0
  • 2- strtok (-NULL,...): a\01\0b=2;c=3\0

strtok , non-NULL str, , (, , ), , , NULL.

When you call strtok again with the non-NULL argument, this is the only place where the state is saved, it is overwritten by what strtok treats as a new string of 3 characters and NULL ( a=1\0), since strtok can no longer remember the original input characteristics. Thus, the record is set to NULL at the end of the loop at the first iteration, because strtok thinks about it at the end of its (much shorter than expected!) Input line.

Check out strtok_r.

+1
source

Source: https://habr.com/ru/post/1722756/


All Articles