在sprintf函数中添加逗号(Add comma in a sprintf function)

编程入门 行业动态 更新时间:2024-10-28 14:36:26
在sprintf函数中添加逗号(Add comma in a sprintf function)

我在看主题: 如何格式化一个数字从1123456789到1,123,456,789在C?

所以我根据现有代码安装了我的代码。

void printfcomma(char *buf, const char* text int n) { if (n < 1000) { sprintf(buf, "%s %d", text, n); return; } printfcomma(buf, n / 1000); sprintf(buf, "%s ,%03d", text, n %1000); return; }

sprintf只返回最后的3位数字。 例如: ,536

有谁知道他们为什么不显示其他数字

I was looking at topic: How to format a number from 1123456789 to 1,123,456,789 in C?

So I mounted my code based on an existing one.

void printfcomma(char *buf, const char* text int n) { if (n < 1000) { sprintf(buf, "%s %d", text, n); return; } printfcomma(buf, n / 1000); sprintf(buf, "%s ,%03d", text, n %1000); return; }

sprintf is only returning the final 3 digits. Example: ,536

Does anyone have any idea why they are not showing the other numbers

最满意答案

你在覆盖。

你应该做sprintf(s+ strlen(s),"abcde");

void printfcomma(char *buf,int n) { if (n < 1000) { sprintf(buf+strlen(buf), "%d", n); return; } printfcomma(buf, n / 1000); sprintf(buf+strlen(buf), ",%03d", n %1000); return; }

在调用函数

memset(s,0,sizeof(s));// s is the char array. printfcomma(s,100000536);

产量

100,000,536

You are overwriting.

You should do sprintf(s+ strlen(s),"abcde");

void printfcomma(char *buf,int n) { if (n < 1000) { sprintf(buf+strlen(buf), "%d", n); return; } printfcomma(buf, n / 1000); sprintf(buf+strlen(buf), ",%03d", n %1000); return; }

In calling function

memset(s,0,sizeof(s));// s is the char array. printfcomma(s,100000536);

Output

100,000,536

更多推荐

本文发布于:2023-07-27 15:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1292266.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:逗号   函数   sprintf   function   comma

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!