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

C code 字符串与整数的相互转化

时间:2016-06-21 10:54:45      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

 1 #include<stdio.h>
 2 int str_to_int(const char *str,int *num);
 3 void int_to_str(char str[],const int strLen,const int num);
 4 
 5 int main(int argc,char *argv[])
 6 {
 7     char str[16];
 8     int ret = 0,n = 0;
 9     while(1)
10     {
11         scanf("%s",str);
12         ret = str_to_int(str,&n);
13         if(ret == 0)
14         {
15             printf("%d\n",n);
16             int_to_str(str,16,n);
17             printf("%s\n",str);
18         }
19         else
20         {
21             printf("error\n");
22         }
23     }
24     return 0;
25 }
26 
27 int str_to_int(const char *str,int *num)
28 {
29     int sign = 1;
30     *num = 0;
31     const char *p = str;
32     while(*p != \0)
33     {
34         if( *p >= 0 && *p <= 9 )
35         {
36             *num = *num * 10 + *p - 0;
37             p++;
38         }
39         else if( *p == - && *num == 0)
40         {
41             sign = -1;
42             p++;
43         }
44         else
45         {
46             return -1;
47         }
48     }
49     *num *= sign;
50     return 0;
51 }
52 
53 void int_to_str(char str[],const int strLen,const int num)
54 {
55     int tmp = 0,n = 0,i = 0;
56     if(num < 0)
57     {
58         n = -num;
59         i = 1;
60     }
61     while(n != 0)
62     {
63         tmp = tmp * 10 + n%10;
64         n /= 10;
65     }
66     while(i<strLen && tmp != 0)
67     {
68         str[i++] = tmp % 10 + 0;
69         tmp /= 10;
70     }
71 }

 

C code 字符串与整数的相互转化

标签:

原文地址:http://www.cnblogs.com/tangxin-blog/p/5602693.html

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