字符串转化成int

将str转化成int

#include
#include
int err = 0;
int str_to_int(char *s)
{
    long sum = 0;
    bool isPositive = true;
    bool isZeroStart = true;
    bool flag = false;
    char c;
    int maxInt = 0x7fffffff;
    bool flag2;
    bool isNumStart = false;

    while (*s != '\0') {
    c = *s;
    flag = (c >= '0' && c <= '9');

    if (c == '-') {
        if (isNumStart) {
        err = 9;
        printf("- is illegal");
        return -1;
        }
        isPositive = false;
        s++;
    } else if (c == '0' && isZeroStart) {
        isNumStart = true;
        s++;

    } else if (c == '+') {
        if (isNumStart) {
        err = 9;
        printf("+ is illegal");
        return -1;
        }

        if (*(s + 1) == '\0') {
        err = 10;
        printf("num is +\n");
        return -1;
        }
        flag2 = (*(s + 1) >= '0' && *(s + 1) <= '9');
        if (!flag2) {
        err = 11;
        printf("num is ilegal\n");
        return -1;
        }
        ++s;
    } else if (flag) {
        sum = sum * 10 + c - '0';
        isNumStart = true;
        if (sum >= maxInt) {
        break;
        }
        isZeroStart = false;
        ++s;
    } else {
        err = 11;
        printf("num is ilegal\n");
        return -1;

    }

    }
    if (isPositive) {
    return sum;
    }
    return -sum;
}

int main(int argc, char *argv[])
{

    if (argc != 2) {
    printf("input num please\n");
    return -1;
    }

    char *str = argv[1];
    int num = str_to_int(str);

    if (err) {
    printf("parse str to num is err\n ");
    return -1;
    }
    printf("num = %d\n", num);
    return 0;
}

该程序支持+,-开头,允许000开头

你可能感兴趣的:(字符串转化成int)