在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
更多推荐
发布评论