C/C++如何将一个数字三位三位加逗号

3 篇文章 0 订阅

C语言版: 

#include<stdio.h>
#include<string.h>
#include<stdarg.h>

void longToStr(long l,char* buf)
{
    char str[20];
    int len;
    int index;
    int offset=0;

    sprintf(str,"%d",l); //转为字符串
    len = strlen(str);

    memset(buf,0,20);

    strncat(buf,str+offset,len%3);
    offset +=len%3;
    if((len%3)&&(len>3))
    {
       strcat(buf,",");//插入逗号
    }
    for(index = len-3; index > 0; index -= 3)
    {
        strncat(buf,str+offset,3);
        offset +=3;
        if(index/3)
        {
            strcat(buf,",");//插入逗号
        }
    }
    strcat(buf,str+offset);

}
void floatToStr(float f,char* buf)
{
    char str[20];
    int len;
    int index;
    int offset=0;

    sprintf(str,"%.2f",f); //转为字符串
    len = strlen(str) - 3;

    memset(buf,0,20);

    strncat(buf,str+offset,len%3);
    offset +=len%3;
    if((len%3)&&(len >3))
    {
       strcat(buf,",");//插入逗号
    }
    for(index = len-3; index > 0; index -= 3)
    {
        strncat(buf,str+offset,3);
        offset +=3;
        if(index/3)
        {
            strcat(buf,",");//插入逗号
        }
    }
    strcat(buf,str+offset);

}
int main()
{
    long l = 1234567890;
    float f = 12345678.56;
    char buf[20];
    longToStr(l,buf);
    printf("%s\n",buf);
    floatToStr(f,buf);
    printf("%s\n",buf);
    return 0;
}

C++版:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    long l;
    cin>>l;
    string str;
    str = to_string(l); //转为字符串
    size_t len = str.length();
    for(int index =(int) len-3; index > 0; index -= 3)
      str.insert(index, ",");//插入逗号。
    cout<<str<<endl;//输出结果。
    return 0;
}

 

  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值