首页 > 其他 > 详细

为下面的函数原型编写函数定义:int ascii_to_integer(char *str)

时间:2015-04-04 10:42:19      阅读:366      评论:0      收藏:0      [点我收藏+]

为下面的函数原型编写函数定义:

int ascii_to_integer(char *str);

这个字符串参数必须包含一个或者多个数字,函数应该把这些数字字符转换为整数并返回这个整数。如果字符串参数包含了任何非数字字符,函数就返回零。请不必担心算数溢出。

提示:这个技巧很简单:你每发现一个数字,把当前值乘以10,并把这个值和新的数字所代表的值相加。字符指针减去‘0’即将其对应的ASCII码值转换为整型。

#include <stdio.h>
int ascii_to_integer(char *str)
{
    int i=0;
    int m=0;
    int sum=0;
    char *ch = str;
    while(*ch != '\0')
    {
        if(*ch<48 || *ch>57)    //判断字符是否是数字
            return 0;
        i++;
        ch++;
    }
    ch=str;
    for(;m<i;m++)
    {
        sum=sum*10+(*(ch+m)-'0');   //减'0'就是将ASCII转换为整形
    }
    return sum;
}
int main()
{
    char *str="123";
    int n;
    n=ascii_to_integer(str);
    printf("%d\n",n);
    return 0;
}
技术分享

为下面的函数原型编写函数定义:int ascii_to_integer(char *str)

原文:http://blog.csdn.net/zhongqi0808/article/details/44871057

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!