Hello,

I'm having some troubles working with strtok. I'm having a string of numbers I want to put in an array, and say from the list I want to get an array with 1,3,5,6,7,8,9,10,12,13,14.

First I just wanted to see the single numbers in one place and split that 5-9 in another place as it would need to be treated differently. But after the first 5-9, where it splits the 5-9, properly into 5 and 9, it doesn't do anything more.

Probably ain't the most efficient code, but been trying to make it work one way or another, so thats why i got all those printfs.

Why is pch going NULL where as with no "if" code, it properly parses the whole string by ",".

/* test for input of a list */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
	char str[]="1,3,5-9,10,12-14";
	char *pch;
	char *pch1;
	char *temp;
	int i;

	pch = strtok(str,",");
	while (pch != NULL)
	{
		printf("debug0 %s\n",pch);
		temp = strdup(pch);
		pch1 = strchr(temp,'-');
		printf("debug1 %s\n",temp);
		printf("debug2 %s\n",pch);
		if (pch1 != NULL)
		{
			pch1 = strdup(temp);
			pch1 = strtok(pch1,"-");
			while (pch1 != NULL)
			{
				i = atoi(pch1);
				printf("p %d\n",i);
				pch1 = strtok(NULL,"-");
			}
			printf("debug3 %s\n",pch);
		}
		else {
		i = atoi(pch);
		printf("%d\n",i);
		}
		free(temp);
		free(pch1);
		printf("debug5 %s\n",pch);
		pch = strtok(NULL,",");
		printf("debug6 %s\n",pch);
	}
	return 0;
}

When I deal with a string like this, that just isn't "quite right", the first thing I like to do, is make it "right".

char str[]="1,3,5-9,10,12-14";

One pass through a for loop would remove both the comma's, and replace the hyphens with a space. Then, use sscanf(), to get all the numbers.I don't have to move the end of string char.

And Welcome to the Forum, Aimbo! ;)

Edited 5 Years Ago by Adak: n/a

In this case simply replacing the hyphens with spaces will not do it. For example 5-9 means 5, 6, 7, 8 and 9. Assuming that is the case, the code in lines 22-33 won't work. You need to extract the two numbers in the string "5-9" then create a loop that processes all the numbers between (and including) those two.

Oh of course! I thought it was just "dirty" input, but the hyphen has to be dealt with if it means "continue the numbers in series, from left to right".

This article has been dead for over six months. Start a new discussion instead.