Thread: string tok to char arrays

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    13

    string tok to char arrays

    hi i am having some trouble with string tokenising....

    Code:
    
    char line "40,2,240";
    
    char *result;
    char age[20];
    char hieght[20];
    char wieght[20];
    
    
    
        result= strtok(line,","))!=NULL)
        strcpy(age,result);
    
        printf("1st age :%s:\n",age);
    
        result= strtok(line,","))!=NULL)
        strcpy(height,result);
    
       result= strtok(line,","))!=NULL)
        strcpy(age,result);
    
    
        result= strtok(line,","))!=NULL)
        strcpy(wieght,result);
    
        if(strtok(line,","))==NULL)
             printf("end\n");
    
    
    printf("age  :%s: \n",age);
    which produces

    Code:
    1st age is 20;
    age ::;
    end

    so i guess what is happening is that result (char*) is pointing to the different memory locations of the portion of the string (line) and that when i get down the bottom result is pointing to a null.....

    but my question is how do i avoid the referencing problem ??? especially if i want to do this thousands of times over a file ???

    ie the idea is cut the line up and then print the char arrays ??

    have been playing around with this for ( embarrassingly) days
    thanks

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    on subsequent calls strtok should get NULL as first parameter

    first line of your code could not be compiled, what you really have?
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  2. newbie needs help with code
    By compudude86 in forum C Programming
    Replies: 6
    Last Post: 07-23-2006, 08:54 PM
  3. Passing pointers to arrays of char arrays
    By bobthebullet990 in forum C Programming
    Replies: 5
    Last Post: 03-31-2006, 05:31 AM
  4. How do i un-SHA1 hash something..
    By willc0de4food in forum C Programming
    Replies: 4
    Last Post: 09-14-2005, 05:59 AM
  5. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 12:03 AM