How to convert a string to integer in C?

后端 未结 12 1553
清酒与你
清酒与你 2020-11-22 01:40

I am trying to find out if there is an alternative way of converting string to integer in C.

I regularly pattern the following in my code.

char s[] =         


        
12条回答
  •  梦如初夏
    2020-11-22 01:58

    This function will help you

    int strtoint_n(char* str, int n)
    {
        int sign = 1;
        int place = 1;
        int ret = 0;
    
        int i;
        for (i = n-1; i >= 0; i--, place *= 10)
        {
            int c = str[i];
            switch (c)
            {
                case '-':
                    if (i == 0) sign = -1;
                    else return -1;
                    break;
                default:
                    if (c >= '0' && c <= '9')   ret += (c - '0') * place;
                    else return -1;
            }
        }
    
        return sign * ret;
    }
    
    int strtoint(char* str)
    {
        char* temp = str;
        int n = 0;
        while (*temp != '\0')
        {
            n++;
            temp++;
        }
        return strtoint_n(str, n);
    }
    

    Ref: http://amscata.blogspot.com/2013/09/strnumstr-version-2.html

提交回复
热议问题