码迷,mamicode.com
首页 > 其他好文 > 详细

将数字字符转化为整数

时间:2014-11-24 22:21:03      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   div   log   bs   

《C和指针》第7章第3道编程题:

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

 int ascii_to_integer( char *string ); 

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

 1 /*
 2 ** 把数字字符串转化为整数
 3 */
 4 
 5 #include <stdio.h>
 6 
 7 int ascii_to_integer( char *string );
 8 
 9 int 
10 main()
11 {
12     char string[100];
13     gets( string );
14     printf( "%d", ascii_to_integer( string ) );
15     return 0;
16 }
17 
18 /*
19 ** 字符串包含一个或多个数字,函数把数字
20 ** 字符转换为整数,并返回整数。
21 ** 如果字符串中包含非数字字符,函数返回0
22 */
23 int 
24 ascii_to_integer( char *string )
25 {
26     char *sp = string;
27     int result = 0;
28     
29     while( *sp != \0 )
30     {
31         /*
32         ** 如果字符串中包含非数字字符,函数返回0
33         */
34         if( *sp < 0 || *sp > 9 )
35             return 0;
36         /*
37         ** 把当前值乘以10后加上新转化的数字
38         */
39         result = result * 10 + *sp - 0;
40         
41         sp ++;
42     }
43     
44     return result;
45 }

 

将数字字符转化为整数

标签:style   blog   io   ar   color   sp   div   log   bs   

原文地址:http://www.cnblogs.com/zouhongmey/p/4119661.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!