- /**
- * 格式化输出字符串
- *
- *
- * 输入 | 输出
- *----------------|---------------------
- * 空 | $0.00
- * 1 | $0.01
- * 12 | $0.12
- * 123 | $1.23
- * 1234 | $12.34
- * 12345 | $123.45
- * 123456 | $1,234.56
- * 1234567 | $12,345.67
- * 12345678 | $123,456.78
- * 123456789 | $1,234,567.89
- * ---------------|---------------------
- *
- *
- * @file format_1.c
- * @brief
- * @author struggleLinux@gmail.com
- * @version 1.0
- * @date 2011-05-10
- */
- #include <stdio.h>
- #include <string.h>
- /**
- *美元货币转换
- * @brief dollars
- *
- * @param dest
- * @param src
- */
- void dollars( char *dest ,char const *src );
- int main()
- {
- char src[20] ;
- char dest[20] ;
- char * str;
- str = src;
- loop:puts("请输入数字:");
- scanf("%s",src);
- if( strlen(src) > 20 ){
- puts("字符串的长度不能大于20!");
- goto loop;
- }
- while( *str != '\0' ){
- if( !isdigit(*str) ){
- puts("请填写正确格式!");
- goto loop;
- }
- str++;
- }
- dollars(dest,src);
- printf("$%s\n",dest);
- return 0;
- }
- void dollars( char *dest ,char const *src )
- {
- int lenght,i,k ;
- char * start,temp;
- start = dest;
- lenght = strlen(src);
- if( lenght < 3 ){
- //格式化长度小于3的数字字符串
- for( k = 0 ;k < 2 ;k++ ){
- if(*(src+lenght-k-1) == '\0')
- *start++ = '0';
- else
- *start++ = *(src+lenght-k-1);
- if( k == 1 ){
- *start++ = '.';
- *start++ = '0';
- }
- }
- }else{
- //'.'、',' 的插入判断
- for(i = 1 ; i <= lenght ; i++ ){
- if( i==2 ) {
- *start++ = *(src +lenght -i);
- *start++ = '.';
- }else if( (i-2)%3 == 0 ){
- *start++ = *(src + lenght -i);
- if( i != lenght)
- *start++ = ',';
- }else
- *start++ = *(src + lenght - i);
- }
- }
- *start = '\0';
- //倒序
- while( start > dest ){
- temp = *--start;
- *start = *dest;
- *dest++ = temp;
- }
- }