Thread: strtok problem

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    3

    Question strtok problem

    i write a strtok program, i think should be got some errors but i cant figure it out why.Can anyone please tell me what is the problem of my program? Thanks for helping.
    My program need to convert the string into 1-dimesion array, but it fails.

    Code:
    int main(void){
    
      char words[20][20] = {"we are happy.", "happy,", ",friday." };
      int i, j;
      char delim[] = ",.";
      char *result;
    
      for ( i=0; i<20; i++){
        for( j=0; j<20; j++){
          result = strtok( &words[i][j], delim);
         while( result != NULL){
            printf("&#37;s\n", result);
            result = strtok(NULL, delim);
         }
      }
      }
    }
    My Output Supposed to be :

    we
    are
    happy
    happy
    friday

    But after compile my program above, my output is:

    we
    are
    happy
    we
    e
    are
    re
    e
    happy
    appy
    ppy
    py
    y
    happy
    appy
    ppy
    py
    y
    friday
    riday
    iday
    day
    ay
    y


    what is the program error ar? i cant figure it why@
    Last edited by tltying; 04-01-2007 at 01:29 PM.

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    You're running two loops and going through every character. Totally wrong. Only one for loop for each string, not for each char.

    Also, you should include the space char inside delim.

    Try something like this (can't say for sure it works):

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
    	char words[20][20] = {"we are happy.", "happy,", ",friday." };
    	int i;
    	char delim[] = ",. ";
    	char *result;
    
    	for ( i=0; i<20; i++)
    	{
    		result = strtok(words[i], delim); /* Make sure you understand what goes on in here! */
    		while(result != NULL)
    		{
    			printf("&#37;s\n", result);
    			result = strtok(NULL, delim);
    		}
    	}
    	
    	return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM
  2. Replies: 6
    Last Post: 04-28-2006, 12:06 PM
  3. Strange problem - strtok
    By AngKar in forum C Programming
    Replies: 7
    Last Post: 04-23-2006, 07:36 PM
  4. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM
  5. Replies: 5
    Last Post: 11-07-2005, 11:34 PM