padding with sprintf

前端 未结 7 2038
甜味超标
甜味超标 2020-12-17 07:34

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

相关标签:
7条回答
  • 2020-12-17 08:04

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

    0 讨论(0)
  • 2020-12-17 08:04

    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.

    0 讨论(0)
  • 2020-12-17 08:07

    The padding and width come before the type specifier:

    sprintf( buf, "%030d", my_val );
    
    0 讨论(0)
  • 2020-12-17 08:13

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

    0 讨论(0)
  • 2020-12-17 08:20

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

    0 讨论(0)
  • 2020-12-17 08:23

    Try:

    sprintf( buf, "%030d", my_val );
    
    0 讨论(0)
提交回复
热议问题