函数原型
int atoi(const char *str)
函数作用
atoi
函数用于c风格字符串(ctsring),将字符串转化为数字类型,如果转换失败则返回0.例如把“4396”转化为4396.
代码示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int val;
char str[20];
strcpy(str, "98993489");
val = atoi(str);
printf("String value = %s, Int value = %d\n", str, val);
strcpy(str, "tutorialspoint.com");
val = atoi(str);
printf("String value = %s, Int value = %d\n", str, val);
return(0);
}
output:
String value = 98993489, Int value = 98993489
String value = tutorialspoint.com, Int value = 0
atoi的实现
以下为K&R C书中的一种实现方式
int atoi(char s[])
{
int i, n = 0;
for(i = 0; s[i] >= '0' && s[i] <=9; ++i)
n = 10 * n + (s[i] - '0');
return n;
}