1. 程式人生 > >C:atoi 字串轉換成整數

C:atoi 字串轉換成整數

int atoi(char *str)
{
    int sign=1;
    int result=0;
    //去前導空白
    while (isspace(*str)) {
        str++;
    }
    //判斷正負
    if (*str=='-') {
        sign=-1;
    }
    if (*str=='+'||*str=='-') {
        str++;
    }
    //轉換
    while (*str) {
        if (isdigit(*str)) {
            result=(result*10+*str-'0');
        }
        else{
            break;
        }
        str++;
    }
    return result*sign;
}