zoukankan      html  css  js  c++  java
  • 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);
    16             int_to_str(str,16,n);
    17             printf("%s
    ",str);
    18         }
    19         else
    20         {
    21             printf("error
    ");
    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 != '')
    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 }
  • 相关阅读:
    1014. 福尔摩斯的约会
    1009. 说反话
    1002. 写出这个数
    1031. 查验身份证
    1021. 个位数统计
    1006. 换个格式输出整数
    1058. A+B in Hogwarts
    1027. Colors in Mars
    1019. General Palindromic Number
    Windows 新装进阶操作指南
  • 原文地址:https://www.cnblogs.com/tangxin-blog/p/5602693.html
Copyright © 2011-2022 走看看