atoi()函数如何处理非数字情况?

ros*_*ose 2 c atoi

我试图编写自己的atoi()函数实现,并尝试了两个不同的代码:

#include <stdio.h>
#include <string.h>

int myatoi(const char *string);

int main(int argc, char* argv[])
{
    printf("\n%d\n", myatoi("str"));
    getch();

    return(0);
}  

int myatoi(const char *string){
    int i;
    i=0;
    while(*string)
    {
        i=(i<<3) + (i<<1) + (*string - '0');
        string++;
        // Don't increment i!
    }
    return i;
}
Run Code Online (Sandbox Code Playgroud)

#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    int x;
    gets(str);
    printf("%d",myatoi(str));
}

int myatoi(char *str) {

    int res =0;
    int i;

    for (i = 0; str[i]!= '\0';i++) {
        res = res*10 + str[i] - '0';
    }
    return res;
}
Run Code Online (Sandbox Code Playgroud)

这两种情况都适用于输入,例如1999年.

但是,如果我偶然传递用户输入,例如"abcd",它将返回一些数值.我用原版试了一下,atoi()对于这种情况,它返回0.

有人可以向我解释如何处理非数字输入atoi().

unw*_*ind 6

您应该使用isdigit()以查看下一个字符是否是(十进制)数字,并在失败时停止.

您还需要检查并处理前导减号以指示负数.不确定eg --12是否有效atoi(),可能不是.

另外请不要微观优化这样的倍数,不再是90年代了.:)

  • 注意:`atoi()`处理可选的单个前导`-` _和_` +`; `--12`无效. (2认同)