Thread: Strings & strtok(...)

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    30

    Strings & strtok(...)

    Hi, I'm messing with strings today (mostly for learning purposes). I have a text file that I'm going to read from; each row has three numbers:
    1) year
    2) month (as an integer)
    3) numeric value
    like this:
    Code:
    2009 12 22222
    2009 11 33333
    2009 10 55555
    etc...
    The last column (the integers on the right), needs some manipulation before they are printed. I was looping through and trying to to set an integer to keep track of the third string on the right (1,2,3 ,1,2,3, 1,2,3...etc ); it is supposed to count to three, but it never goes above one.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void seperateByCommaOrSpaceAndPrintOnePerLine(char *str){
    	char *result; 	
    	
    	//if result = NULL, then result = false.
    	int num = 1;
    	while ((result = strtok(str, " ,"))){ //   <---contains the delimiters that determine the token
    										//    i.e., this is actually a collection of tokens, space and comma. 
    										//    Either a space, comma, or space and comma will 'delimit' the string.
    		printf("%s %d\n", result, num);
    		str = NULL; 
    					
    	
    		num++;
    		if (num == 4){num = 1;}
    	}
    }
    
    int main(){
    	char names[1000][100]; //first square bracket is the number of strings, 2nfd square brackret is the size of each string.
    	int count = 0;
    	while (scanf("%s", names[count]) != EOF) {
    		count++;
    	}
    	
    	
    	printf("\n\n\n\n");
    	
    	
    	int j = 0;
    	while(j <= count){
    		//printf("%s\n", names[j]);
    		seperateByCommaOrSpaceAndPrintOnePerLine(names[j]);
    		j++;
    	}
    
    	return 0;
    }
    Last edited by Roger; 12-24-2009 at 02:28 PM.

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    You are setting str to null inside your while loop.

    Plus, you're not really using strtok correctly. Check the reference.
    Mainframe assembler programmer by trade. C coder when I can.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strings Program
    By limergal in forum C++ Programming
    Replies: 4
    Last Post: 12-02-2006, 03:24 PM
  2. Programming using strings
    By jlu0418 in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2006, 08:07 PM
  3. Breaking strings without using strtok()
    By hykyit in forum C Programming
    Replies: 2
    Last Post: 08-23-2005, 05:40 AM
  4. Reversing strings using strtok()
    By Sure in forum C Programming
    Replies: 5
    Last Post: 06-27-2005, 05:33 PM
  5. Replies: 1
    Last Post: 09-05-2004, 06:42 PM