47

I have a dummy question. I would like to print an integer into a buffer padding with 0 but I cannot sort it out the sprintfformat. I am trying the following

char buf[31];
int my_val = 324;
sprintf( buf, "%d030", my_val );

hoping to have the following string

"000000000000000000000000000324"

what am I doing wrong? It doesn't mean pad with 0 for a max width of 30 chars?

7 Answers 7

98

"%030d" is the droid you are looking for

1
  • 4
    "The droids you are looking for are in the manual. They are called width and precision." :-)
    – Jens
    May 16, 2012 at 13:27
14

You got the syntax slightly wrong; The following code produces the desired output:

char buf[31];
int my_val = 324;
sprintf( buf, "%030d", (int)my_val );

From Wikipedia's Article on Printf:

[...] printf("%2d", 3) results in " 3", while printf("%02d", 3) results in "03".
1
  • 4
    Why do you need to cast my_val to int when it's already an int?
    – Kevin Ji
    May 25, 2011 at 2:17
7

The padding and width come before the type specifier:

sprintf( buf, "%030d", my_val );
5

Try:

sprintf( buf, "%030d", my_val );
1
  • 2
    You probably already know this, but using snprintf style functions where you specify the buffer length is a good habit to get yourself in, as it helps prevent buffer overflows.
    – Matthew
    May 24, 2011 at 21:20
3

Your precision and width parameters need to go between the '%' and the conversion specifier 'd', not after. In fact all flags do. So if you want a preceeding '+' for positive numbers, use '%+d'.

2

It's %030d, with type-letter at the end.

1

A fairly effective version that doesn't need any slow library calls:

#include <stdio.h>

void uint_tostr (unsigned int n, size_t buf_size, char dst[buf_size])
{
  const size_t str_size = buf_size-1;

  for(size_t i=0; i<str_size; i++)
  {
    size_t index = str_size - i - 1;
    dst[index] = n%10 + '0';
    n/=10;
  }
  dst[str_size] = '\0';
}


int main (void)
{
  unsigned int n = 1234;
  char str[6+1];
  uint_tostr(n, 6+1, str);
  puts(str);
}

This can be optimized further, though it is still probably some hundred times faster than sprintf as is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.