Thread: reset strtok()

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Aug 2012
    Posts
    9
    Quote Originally Posted by laserlight View Post
    the solution is to copy the string, then call strtok with the copy.
    What is wrong in my code?
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(void)
    {
        char *pos1, *pos2;
        char string[256];
        
        printf("Enter a string: ");
        fgets(string, 255, stdin);
        
        pos1 = string;
        char copy[strlen(string)+1];
        strcpy(copy, string);
        pos1 = strtok( string, " ,");    
        while (pos1) {
            pos2 = strtok( copy, " ,");
            while (pos2) {
    printf("pos2 %s\n", pos2); //for debug
                if(!strcmp(pos1, pos2) && (string-pos1)<(copy-pos2))
                    puts(pos2);
                pos2 = strtok( NULL, " ,");
            }
    printf("pos1 %s\n", pos1); //for debug
        pos1 = strtok( NULL, " ,");
        }
    
        return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Quote Originally Posted by SashaN View Post
    What is wrong in my code?
    Code:
    pos1 = strtok( string, " ,");    
    while (pos1) {
        pos2 = strtok( copy, " ,");
    You can't use strtok one two different strings simultaneously. The moment you use strtok() on "copy", tokenizing "string" doesn't work any more. The reason is that strtok() saves internally the state of the current string processing, thus if you provide a new string, this information is overwritten.
    If you really want to tokenize two strings you could use the non-standard strtok_r (e.g. supported by the GNU C Library) or strtok_s (new in C11).

    Bye, Andreas

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strtok reset
    By lavinpj1 in forum C Programming
    Replies: 3
    Last Post: 04-25-2006, 06:00 PM
  2. Direct3D won't reset
    By Magos in forum Game Programming
    Replies: 1
    Last Post: 05-10-2004, 01:23 PM
  3. how to reset getline?
    By MKashlev in forum C++ Programming
    Replies: 6
    Last Post: 08-11-2002, 08:51 AM
  4. Is the origin reset...
    By fletch in forum Windows Programming
    Replies: 4
    Last Post: 07-29-2002, 05:59 PM
  5. help why does cnt not reset to 1??
    By datainjector in forum C Programming
    Replies: 4
    Last Post: 07-17-2002, 12:56 AM