C语言实现 字符串转换为整数输出 int ascii_to_integer(char *str);
比如:“123456”这个字符串 用整数表达就是123456;
函数应该把这些数字字符转换为整数并返回这个整数。
如果字符串参数包含了任何非数字字符,函数就返回零。
代码实现:
#include<stdio.h>
#include<string.h>
#include<math.h>
int ascii_to_integer(char *str)
{
int count = 0;
int sum = 0;
count = strlen(str);
if((*str) < 0 && (*str) > 9)
{
return 0;
} //如果不为数字结果返回0
while(count)
{
sum = sum + ((int)*str-48)*(pow(10,count-1)); //因为1的assci码值为49,所以这里统一-48,就可以得到整数的大小
str++;
count--;
}
return sum;
}
int main()
{
char *str = "123456";
int ret = ascii_to_integer(str);
printf("%d\n",ret);
return 0;
}
结果如下:
还没有评论,来说两句吧...