I have two helper functions to break up strings in the format of decimal prices ie. “23.00”, “2.30”
Consider this:
char price[4] = "2.20";
unsigned getDollars(char *price)
{
return atoi(strtok(price, "."));
}
unsigned getCents(char *price)
{
strtok(price, ".");
return atoi(strtok(NULL, "."));
}
Now when I run the below I get a segmentation fault:
printf("%u\n", getDollars(string));
printf("%u\n", getCents(string));
However when I run them seperately without one following the other, they work fine. What am I missing here? Do I have to do some sort of resetting of strtok??
My solution:
With the knowledge about strtok I gained from the answer I chose below, I changed the implementation of the helper functions so that they copy the passed in string first, thus shielding the original string and preventing this problem:
#define MAX_PRICE_LEN 5 /* Assumes no prices goes over 99.99 */
unsigned getDollars(char *price)
{
/* Copy the string to prevent strtok from changing the original */
char copy[MAX_PRICE_LEN];
char tok[MAX_PRICE_LEN];
/* Create a copy of the original string */
strcpy(copy, price);
strcpy(tok, strtok(copy, "."));
/* Return 0 if format was wrong */
if(tok == NULL) return 0;
else return atoi(tok);
}
unsigned getCents(char *price)
{
char copy[MAX_PRICE_LEN];
char tok[MAX_PRICE_LEN];
strcpy(copy, price);
/* Skip this first part of the price */
strtok(copy, ".");
strcpy(tok, strtok(NULL, "."));
/* Return 0 if format was wrong */
if(tok == NULL) return 0;
else return atoi(tok);
}
Because
strtok()modifies the input string, you run into problems when it fails to find the delimiter in thegetCents()function after you callgetDollars().Note that
strtok()returns a null pointer when it fails to find the delimiter. Your code does not check thatstrtok()found what it was looking for – which is always risky.Your update to the question demonstrates that you have learned about at least some of the perils (evils?) of
strtok(). However, I would suggest that a better solution would use juststrchr().First, we can observe that
atoi()will stop converting at the ‘.‘ anyway, so we can simplifygetDollars()to:We can use
strchr()– which does not modify the string – to find the'.'and then process the text after it:Quite a lot simpler, I think.
One more gotcha: suppose the string is 26.6; you are going to have to work harder than the revised
getCents()just above does to get that to return 60 instead of 6. Also, given 26.650, it will return 650, not 65.