strtok help

Discussion in 'C' started by rajib, May 19, 2007.

  1. rajib

    rajib New Member

    Joined:
    May 18, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Hi this is the code -

    -----------------------------------------------------------
    Code:
    FILE *fp = fopen ("C:\\Temp\\in2.txt", "r");
    
    fgets(line, sizeof(line), fp);
    
    printf("line is %s\n", line);
    sub_str = strtok_r(line, "~");
    printf("Printing strings - %s \n", sub_str);
    
    sub_str = strtok_r(NULL, "~");
    printf("Next string - %s \n", sub_str);
    --------------------------------------------------------

    The line is -
    ITem~G!!~~~~34

    The O/P is -
    ITem
    G!!

    HOW CAN I EXTRACT THE NULL VALUES ALSO IN BETWEEN? STRTOK() IGNORES IF THERE ARE NULL IN BETWEEN....

    Please help. :mad:
     
    Last edited by a moderator: May 19, 2007
  2. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    http://www.daweidesigns.com
    There's no need to yell.

    There are no NULL values in between. I presume you mean how does one extract all values in the string, which would include the "34". The '~' is not a NULL value, it is the chosen delimiter. You need to read the documentation of strtok. On the first call, you pass strtok a pointer to the string. It returns the first token, tokens being defined by the delimiters. To get the next token, you pass a NULL pointer rather than a pointer to the string. You get one additional token for each call. You stop when strtok returns a NULL pointer.

    Logical reasoning, then, suggests that we put the subsequent calls in a loop and break the loop when strtok returns NULL.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice