在 sprintf 函数中添加逗号

Add comma in a sprintf function

本文关键字:添加 sprintf 函数      更新时间:2023-10-16

>我在看主题:如何在 C 中将数字从 1123456789 格式化为 1,123,456,789?

所以我基于现有的代码挂载了我的代码。

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

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

您正在覆盖。

你应该做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

正如@coderredoc所回答的那样,代码正在覆盖buf

调用 strlen() 的替代方法是利用 sprintf() 的返回值。

sprintf 函数返回数组中写入的字符数,不计算终止 null 字符,如果发生编码错误,则返回负值。 C11dr §7.21.6.6 3

进一步:代码也应该处理负数。

const char* text用途尚不清楚。 下面的示例代码不使用它。

int printfcomma(char *buf, int n) {
  if (n > -1000 && n < 1000) { // avoid (abs(n) < 1000) here.  abs(INT_MIN) is a problem
    return sprintf(buf, "%d", n);
  }
  int len = printfcomma(buf, n / 1000);
  if (len > 0) {
    len += sprintf(buf + len, ",%03d", text, abs(n % 1000));  // do not print `-`
  } 
  return len;
}

用法

char s[sizeof(int)*CHAR_BIT]; // Somehow, insure buffer size is sufficient.
printfcomma(s, INT_MIN);
puts(s); --> -2,147,483,648