C语言-字符串函数:atoi() 字符串转int型(有bug)

说明

atoi (表示 ascii to integer),将字符串转成int,有bug,不推荐使用

替代函数,见 链接

bug1

将 "234abc" 转换成数字,结果是 234,即:将开头数字部分进行转换,遇到非数字就不转换了

#include "stdafx.h"
#include <stdlib.h>

int main(int argc, char* argv[])
{
    char s[128]="234abc";
    int i=atoi(s);
    printf("%d\n",i);
    return 0;
}

bug2

如果字符串的开头 不是数字,返回0;如果转换的字符串是"0",那么也返回0,也就是说:可能无法分辨是否成功

#include "stdafx.h"
#include <stdlib.h>

int main(int argc, char* argv[])
{
    char s[128]="0";//字符串是0,返回值是0
    int i=atoi(s);
    printf("%d\n",i);


    char s2[128]="a";//字符串开头不是数字,返回值也是0
    int i2=atoi(s2);
    printf("%d\n",i2);

    return 0;
}

原文出处:/show_1IX2tauMox76.html