在数字字符串中插入千分符

View Code
  1 #include<stdio.h>
  2 
  3 #include<string.h>
  4 
  5 #include<stdlib.h>
  6 
  7 
  8 
  9 
 10 void PrintString(char *p,char *In_num)
 11 
 12 {
 13 
 14     int i=0;
 15 
 16     int lenth;
 17 
 18     if(strlen(p)<4)
 19 
 20         puts(In_num);
 21 
 22     else
 23 
 24     {
 25 
 26         lenth=strlen(p)%3;
 27 
 28         for(i=0;p[i]!='\0';i++)
 29 
 30         {
 31 
 32             printf("%c",p[i]);
 33 
 34             if((i+1)%3==lenth&&p[i+1]!='\0')
 35 
 36                 printf("%c",44);
 37 
 38         }
 39 
 40     }
 41 
 42 }
 43 
 44 int main(void)
 45 
 46 {
 47 
 48     char *In_num,*str;
 49 
 50     int i=0;
 51 
 52     In_num=(char *)malloc(sizeof(char *));
 53 
 54     str=(char *)malloc(sizeof(char *));
 55 
 56     if(In_num==NULL) //检查分配是否成功;
 57 
 58     {
 59 
 60         printf("Can't get so many values.\n");
 61 
 62         exit(1);
 63 
 64     }
 65 
 66     printf("Please input the num_string:\n");
 67 
 68     gets(In_num); 
 69 
 70     strcpy(str,In_num);
 71 
 72     char *p;
 73 
 74     char *n[2];
 75 
 76     p=strtok(str,".");
 77 
 78     while(p)
 79 
 80     {
 81 
 82         n[i++]=p;
 83 
 84         p=strtok(NULL,".");
 85 
 86     }
 87 
 88     PrintString(n[0],In_num);
 89 
 90     if(i==2&&strlen(n[0])>=4)
 91 
 92     {
 93 
 94         printf(".");
 95 
 96         for(i=0;n[1][i]!='\0';i++)
 97 
 98         {
 99 
100             printf("%c",n[1][i]);
101 
102         }
103 
104     }
105 
106     printf("\n");
107 
108     free(In_num); //释放;
109 
110     free(str);//释放; 
111 
112     getchar();
113 
114     return 0;
115 
116 }

 

posted @ 2012-06-05 20:03  特务小强  阅读(792)  评论(0编辑  收藏  举报