Thread: Using strtok on separate functions

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    20

    Using strtok on separate functions

    I've used strtok() before to parse a string, but for some reason I cannot seem to use it in separate functions correctly. I'm trying to separate strings in one function and initialize them in the calling function. Can someone tell me where I'm going wrong?

    Code:
    void get_tokens(char *line, char *lbl, char *opertr, char *opernd){    
        lbl=strtok(line, " ");
        opertr = strtok(NULL, " ");    
        opernd = strtok(NULL, " ");
    }  
    
    void pass1(){
       char  inp_line[INP_LENGTH + 1],
             label[NAME_LENGTH + 1],    
             oper[OP_LENGTH + 1],  
             opnd[OPND_LENGTH + 1]; 
       
       get_tokens(inp_line, label, oper, opnd);
    }

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Simply put: strtok() returns a pointer but it won't actually copy over the data. Try capturing the return value in a different point and then use strcpy() afterwards to copy the data over.

    Example:
    Code:
    void get_tokens(char *const line, char *const lbl, char *const opertr, char *const opernd) {
      char *temp = strtok(line, " ");
      strcpy(lbl, temp);
      temp = strtok(NULL, " ");
      strcpy(opertr, temp);
      /* ... */
    }
    Now I should mention that you really should check the return value of strtok() for NULL before calling strcpy().

  3. #3
    Registered User
    Join Date
    Sep 2004
    Posts
    20
    Thanks a lot Thantos. For some reason I didn't even think of using strcpy( ). That did the trick.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Is it legal to have functions within functions?
    By Programmer_P in forum C++ Programming
    Replies: 13
    Last Post: 05-25-2009, 11:21 PM
  2. Trouble with strtok()
    By BianConiglio in forum C Programming
    Replies: 2
    Last Post: 05-08-2004, 06:56 PM
  3. Problems with inline functions in visual c++
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2002, 03:14 AM
  4. Passing data/pointers between functions #2
    By TankCDR in forum C Programming
    Replies: 1
    Last Post: 11-02-2001, 09:49 PM
  5. functions & external files
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 10-24-2001, 03:13 AM