Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在sprintf函数中添加逗号_C++_C - Fatal编程技术网

C++ 在sprintf函数中添加逗号

C++ 在sprintf函数中添加逗号,c++,c,C++,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); ret

我在看主题:

所以我在现有代码的基础上安装了我的代码

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;
}
void printfcomma(char*buf,const char*text int n){
如果(n<1000){
sprintf(buf,“%s%d”,文本,n);
回来
}
printfcomma(基本单位,n/1000);
sprintf(buf,“%s,%03d”,文本,n%1000);
回来
}
sprintf只返回最后3位数字。示例:,536

有人知道为什么他们没有显示您正在覆盖的其他数字吗

你应该做
sprintf(s+strlen),“abcde”)

输出
100000536

正如所回答的,代码写得太多了
buf

调用
strlen()
的另一种方法是利用
sprintf()
的返回值

sprintf
函数返回数组中写入的字符数,不计算终止的空字符,如果发生编码错误,则返回负值。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;
}

这甚至不应该编译。您调用
printfcomma(buf,n/1000)但是您的函数是编写的
void printfcomma(char*buf){
…很抱歉,在将代码传递给post时出错,我编辑了,我明白了,现在您可以向我解释其他内容,我想扩展此函数看看主题。例如,如果我添加一个
%s
it me printa it 3x,那么
test:,536
`test:,000`` test:100`@carolzinha.:据我所知,这是另一个单独的问题。但请注意在代码中,我可以看到它可以被重用。你可以试着理解它并重用。这个答案解决了你的问题。对于其他问题,如果你不理解,在你尝试了足够多之后再问一个单独的问题。
memset(s,0,sizeof(s));// s is the char array.
printfcomma(s,100000536);
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