为下面的函数原型编写函数定义:
int ascii_to_integer(char *str);
这个字符串参数必须包含一个或者多个数字,函数应该把这些数字字符转换为整数并返回这个整数。如果字符串参数包含了任何非数字字符,函数就返回零。请不必担心算数溢出。
提示:这个技巧很简单:你没发现一个数字,把当前值乘以10,并把这个值和新的数字所代表的值相加。
1234yyyyyyyyyy 0
rr222222 0
33333 0
#include<stdio.h>
int ascii_to_integer(char str[])
{
int n = 0;
int i;
while(str[i])
{
if(str[i] >= 'a'&& str[i] <= 'z')
return 0;
else
n = 10 * n + (str[i] - '0');
i++;
}
return n;
}//数组
int ascii_to_integer2(char *str)
{
int n = 0;
int i;
while(str[i])
{
if(str[i] >= 'a'&& str[i] <= 'z')
return 0;
else
n = 10 * n + (str[i] - '0');
i++;
}
return n;
}//指针
int main()
{
printf("%d\n",ascii_to_integer("128 ue u3"));
printf("%d\n",ascii_to_integer2("1 w1 t4"));
return 0;
}