字符串转整形

来源:互联网 发布:vs2017写c语言 编辑:程序博客网 时间:2024/05/01 03:00
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>#include <assert.h>// return: 0 errorint Str2Int(const char* _pInput){    if (NULL == _pInput || strlen(_pInput) > 11 || _pInput[0] == '0') // max length 11 (include '-')    {        return 0;    }    // check valid    int i = 0;    int bMinus = 0;    if (*_pInput == '-')    {        i ++;        bMinus = 1;    }    if ((strlen(_pInput) == 10 || strlen(_pInput) == 11)         && isdigit(_pInput[i]) && ((_pInput[i] - '0') > 3)) // max start num 3    {        return 0;    }    for (i; i < strlen(_pInput); i++)    {        if (!isdigit(_pInput[i]))        {            return 0;        }    }    //calc    unsigned int Sum = 0;    int max = 0x7fffffff;    int min = 0x80000000;    //unsigned int umax = 0xffffffff;    //printf("max = %d, min = %d, umax = %u\n", max, min, umax);    const char* pBegin = _pInput;    // check minus    if (bMinus)    {        pBegin ++;    }    while (*pBegin != '\0')    {        Sum = Sum * 10 + *pBegin - '0';        pBegin ++;        //printf("Sum = %u\n", Sum);        //check overflow        if ((bMinus && Sum > max + 1) || (!bMinus && Sum > max))        {            return 0;        }    }        int ret = (bMinus) ? -Sum : Sum;        return ret;}int main(int argc, char** argv){    char str[] = "-214748364844";        int nRet = Str2Int(argv[1]);    printf("nRet: %d\n", nRet);        return 0;}

0 0