Problem with strtok and segmentation fault

后端 未结 2 978
眼角桃花
眼角桃花 2020-12-20 20:26

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\";

            


        
2条回答
  •  礼貌的吻别
    2020-12-20 20:44

    Because strtok() modifies the input string, you run into problems when it fails to find the delimiter in the getCents() function after you call getDollars().

    Note that strtok() returns a null pointer when it fails to find the delimiter. Your code does not check that strtok() 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 just strchr().

    First, we can observe that atoi() will stop converting at the '.' anyway, so we can simplify getDollars() to:

    unsigned getDollars(const char *price)
    {
        return(atoi(price));
    }
    

    We can use strchr() - which does not modify the string - to find the '.' and then process the text after it:

    unsigned getCents(const char *price)
    {
        const char *dot = strchr(price, '.');
        return((dot == 0) ? 0 : atoi(dot+1));
    }
    

    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.

提交回复
热议问题