Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to split string by 2 tocken in c++?



  • Hello i want to split string by two token one '$' and ',' and store them into separate string variable. So what mistake i done in below code?

    i made mistake in below code :

    #include <string.h>
    #include <stdio.h>
    
    int main () {
        unsigned char c= 0;
       char str[80] = "1.5,10,1.3$1.5,11,1.4";
       const char s[2] = "$",s1[2]= "," ;
       char *token,*token1;
       
       /* get the first token */
       token = strtok(str, s);
       
       /* walk through other tokens */
       while( token != NULL ) {
          printf( " %s\n", token );
        c++;
          
          if(c%3 != 0)
          token = strtok(NULL, s);
    
          token1 = strtok(str, s1);
          while(token1 != NULL)
          { 
              printf( " %s\n", token1 );
              c++;
              token1 = strtok(NULL, s1);
              
          }
    
       }
       
       return(0);
    }
    

    actually i want to get output as

    1.5,10,1.3
    1.5
    10
    1.3

    1.5
    11
    1.4

    but output comes like below :
    1.5,10,1.3
    1.5
    10
    1.3
    1.5,11,1.4
    1.5


  • Lifetime Qt Champion

    @Qt-embedded-developer Any reason to write C code instead of C++ with Qt classes?



  • @jsulm no reason is there



  • @Qt-embedded-developer
    I'm not going to work through what your code actually does, and how it compares to the output, but you have:

     token = strtok(str, s);
    ...
     token1 = strtok(str, s1);
    

    What do you think this is actually going to do? Once you have called strtok(str, ...); you should only call strtok(NULL, ...); to get another token out of str. strtok(str, ...); alters (writes a \0 into) str. This could be a problem for you.

    More pertinently: strtok(NULL, ...) can only work on the single, last string you called strtok(str, ...) on. Your code seems to go:

    strtok(str, s);
      strtok(str, s1);
        strtok(NULL, s1);
    // then you return to the *outer* loop and go
    strtok(NULL, s);
    

    That last line is now operating on the latest strtok(str, s1) executed, not on the original strtok(str, s) which I believe is what you think it is doing. Maybe that's the cause of your output.

    In any case: don't use strtok() in modern programs. Either use a re-entrant strtok_r() which at least allows multiple separate string to tokenised without interfering with each other. Even then it's bad because it still writes into the string. Or, much better as @jsulm says, use C++ methods instead. You ought no longer be using char []s, char *s, strtok() and so on in your code. That was for C, now we are C++.

    P.S.
    Instead of C code and strtok(), in Qt just use QStrings and QString::split() to do your tokenisation work. You won't have these problems that way.


Log in to reply