Published by
Oct 15, 2008

strtok uses

Score: 3.6/5 (13 votes)
*****
First off, I visit this site quite regularly, but I've never posted. I find lots of help here and thought I'd return the favor. I recently worked on a project that required I use the strtok function. A problem I was running into was that the strtok was changing my original variable. I finally was able to fix my problem to get a successful copy to tokenize without changing the original.



A little background: This is set up as a function of a child class. The char variable is obviously declared elsewhere, but I showed it for the sake of clarity. Also, strcpy_s was used because I have VS, however strcpy works also (parameters would be different). Hopefully with the comments, the rest of the code is clear enough to be understood easily:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char decimalNumber[] = "12.34";

int ChildClass::getNumberBeforeDecimal()
{
	char numBeforeDecimal[6]="";
	char* token; 

	strcpy_s(numBeforeDecimal,                   //copying decimalNumber
            sizeof(numBeforeDecimal),decimalNumber); //to numBeforeDecimal
                                                

	strtok(numBeforeDecimal, ".");
	token = strtok(NULL, "."); //should assign "12" to token
	
	return atoi(token);  //converts the token and returns 12
}


Now, I haven't tested this exact code (feel free to correct it if I made a mistake). I took the code that I originally had written (yes, it worked!) and tried to make it generic enough to be understood without screwing it up. Oh, and I know there's an easier way of getting numbers before a decimal. This is just for the purpose of helping understand one use of strtok. With little effort this could be used to return the numbers after the decimal.

Feel free to post other uses of strtok if you want.

Peace,
S. Jones