padding with sprintf

53,881

Solution 1

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

Solution 2

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".

Solution 3

The padding and width come before the type specifier:

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

Solution 4

Try:

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

Solution 5

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'.

Share:
53,881

Related videos on Youtube

Abruzzo Forte e Gentile
Author by

Abruzzo Forte e Gentile

Updated on July 09, 2022

Comments

  • Abruzzo Forte e Gentile
    Abruzzo Forte e Gentile almost 2 years

    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?

  • Matthew
    Matthew almost 13 years
    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.
  • kevinji
    kevinji almost 13 years
    Why do you need to cast my_val to int when it's already an int?
  • Jens
    Jens almost 12 years
    "The droids you are looking for are in the manual. They are called width and precision." :-)