Getting array values using strtok

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rola248
    New Member
    • Jul 2009
    • 8

    #1

    Getting array values using strtok

    hi all,
    if we use strtok toseparate a line into two parts,say rola : 23

    Code:
    for(i=0;i<index;i++){
    ptr=strtok(line[i],":");
    while(ptr!=NULL)
    {
    strcpy(num[i],ptr);
    ptr=strtok(NULL,":");
    }
    }
    the second part(23) is saved in the array num,,,,,how do we save the first part(rola) in a second array???
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    ptr=strtok(NULL ,":");
    This makes no sense and will always return null. Why even have the while loop?

    I think you want something like:
    strncpy(array2[i], line[i], (ptr-line[i])/sizeof(char));

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      ptr=strtok(NULL ,":");
      This makes no sense and will always return null. Why even have the while loop?
      I think you need to read the strtok documentation yourself. You call it the first time with a pointer to your string and the list of terminators and it returns the first token. Then you call it on subsequent times with a pointer to NULL and the terminators and it returns the 2nd, 3rd ... etc token on the line until it finally returns NULL when there nothing left on the line.

      Strictly speaking there is no need to save the first part, that is what line[i] is after the first call to strtok.

      Generally strtok is a poor library function because it used static internal buffers to perform the tokenisation and so is not re-entrant or thread safe.

      Comment

      • jkmyoung
        Recognized Expert Top Contributor
        • Mar 2006
        • 2057

        #4
        Interesting; I have indeed blundered. See reference:


        You are probably overwriting the first result. I still do not recommend the use of your while loop as you don't really seem to need to loop.

        Comment

        Working...