函數(shù)原型
int atoi(const char *str)
函數(shù)作用
atoi
函數(shù)用于c風(fēng)格字符串(ctsring),將字符串轉(zhuǎn)化為數(shù)字類型博杖,如果轉(zhuǎn)換失敗則返回0.例如把“4396”轉(zhuǎn)化為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的實(shí)現(xiàn)
以下為K&R C書中的一種實(shí)現(xiàn)方式
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;
}