Thread: help me with this strtok

  1. #1
    Registered User
    Join Date
    Jan 2008

    help me with this strtok

    I have the following code:

     char* pch = strtok(line, " ");
          	 int h;
             for (h = 0; pch != NULL; h++){
    	    if (h == 0){
    	     target = StringConstruct(pch);
                pch = strtok(NULL, " ");
                printf("Target %s\n", target); 
    	    else if (strlen(pch) > 1){
    	      strcpy(dep[depIndex], pch);
    	      printf("Dependencies %s\n", dep[depIndex] );
    	   pch = strtok(NULL, "  ");
    if I use this string:

    Name : John

    the strlen of John will be 5 instead of 4

    If I use this

    Name: John Legend

    the strlen of John will be 4 but Legend will be 7, how do I fix this?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Remove the \n from the end of the string before you tokenize, or alternatively, add \n to your list of tokens to break off.

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    Are you by any chance using fgets() to read the input? If so, you may have a '\n' that you can't really see on the back of that string...

       char *p = strrchr(s, '\n');
       if (p) *p = 0;
    will replace the newline with a NUL character and thus shorten the string by one char.

    [And of course, it's not the fault of strtok()]

    [Note: You could, potentially add "\n" to your search string and achieve the same effect - although I would probably just use the first bit of code directly after fgets() to clean up the string generically].

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 20q game problems
    By Nexus-ZERO in forum C Programming
    Replies: 24
    Last Post: 12-17-2008, 05:48 PM
  2. strtok is causing segmentation fault
    By yougene in forum C Programming
    Replies: 11
    Last Post: 03-08-2008, 10:32 AM
  3. trying to use strtok() function to parse CL
    By ohaqqi in forum C Programming
    Replies: 15
    Last Post: 07-01-2007, 09:38 PM
  4. Help debugging my program
    By shoobsie in forum C Programming
    Replies: 4
    Last Post: 07-05-2005, 07:14 AM
  5. Trouble with strtok()
    By BianConiglio in forum C Programming
    Replies: 2
    Last Post: 05-08-2004, 06:56 PM