Thread: How to put a strtok into a char[]

  1. #1
    Registered User
    Join Date
    Aug 2010
    Posts
    42

    How to put a strtok into a char[]

    OK so I have a struct:

    Code:
    struct person{
           int arrivaltime;
           char name[NAME_LEN];
           int num_items;
           };
    I have used fgets to get a line that looks like '1500 ALAN 7'

    Then I used strtok with space as delimiter. I originally had the name as char* name. The strtok worked with that but I was having a problem that when I went back to view values of previous people i would get either the most recent persons name entered or nothing.

    (i.e. If i input 1500 ALAN 7 then 2000 BOB 15 and tried to print alan's info id get
    1500 BOB 7

    So I'm pretty sure doing char name[] will fix that but I cant get this line working:

    Code:
    people[j].name = strtok(NULL, " ");
    It's throwing an incompatible types in assignment. How to I fix it to put the strtok as the correct type?

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    You need to copy the string; you can't assign to an array. strcpy() will work as long as you know that there's enough space in the target. You can be sure there is if you never tokenize a string longer than NAME_LEN bytes long.

  3. #3
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    I would go along like this and try avoid using strtok.

    Code:
    struct person{
           int arrivaltime;
           char name[NAME_LEN];
           int num_items;
           };
    
    
    char User[80];
    
    fgets( User, sizeof(User), stdin);
    sscanf( User, "%d %s %d", &people[i].arrivaltime, people[i].name, &people[i].num_items );
    ssharish
    Life is like riding a bicycle. To keep your balance you must keep moving - Einstein

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. trying to use strtok() function to parse CL
    By ohaqqi in forum C Programming
    Replies: 15
    Last Post: 07-01-2007, 09:38 PM
  2. strtok with "" as delimiter?
    By fanoliv in forum C Programming
    Replies: 15
    Last Post: 06-19-2006, 12:44 PM
  3. Help debugging my program
    By shoobsie in forum C Programming
    Replies: 4
    Last Post: 07-05-2005, 07:14 AM
  4. converting string to integer, for further use
    By shoobsie in forum C Programming
    Replies: 2
    Last Post: 07-01-2005, 03:12 AM
  5. Strtok
    By Unregistered in forum C Programming
    Replies: 5
    Last Post: 10-17-2001, 09:32 PM