C code 字符串与整数的相互转化
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 }