将数字字符转化为整数

《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 }

 

posted on 2014-11-24 21:31  丝工木每  阅读(688)  评论(0编辑  收藏  举报

导航