1

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

carolzinha
  • 101
  • 1
  • 7

2 Answers2

1

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

user2736738
  • 30,591
  • 5
  • 42
  • 56
  • I understand, now you can explain to me something else, I want to expand this function look at the topic. Example if I add a `%s` it me printa it 3x, so `test: ,536` ` test: ,000` ` test: 100` – carolzinha Nov 07 '17 at 19:19
  • @carolzinha.: As far as I know this is another separate question. But looking at the code I can see it can be reused. You can try to understand this and reuse. This answer solves your problem.For other question if you don't understand ask a seperate question after you have tried enough. – user2736738 Nov 07 '17 at 19:23
0

As answered by @coderredoc, code is over-writing buf.

An alternative to calling strlen() is to take advantage of the return value of sprintf().

The sprintf function returns the number of characters written in the array, not counting the terminating null character, or a negative value if an encoding error occurred. C11dr §7.21.6.6 3

Further: code should handle negative numbers too.

const char* text use is unclear. Example code below does not use it.

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;
}

Usage

char s[sizeof(int)*CHAR_BIT]; // Somehow, insure buffer size is sufficient.
printfcomma(s, INT_MIN);
puts(s); --> -2,147,483,648
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256