c++ - printf int to char array with left padded spaces -


i have bit of brain dead moment.

i have store string representation of int char[], ascii representation have left padded spaces. snprintf job.

  char data     [6];   int msg_len = 10;   std::snprintf(data, 6, "%*d", 5, msg_len);   //"   10" <-- ok 

i wonder if there more elegant way it. have access c++11 there's a bit of problem, think snprintf add terminating character, , have avoid that. have intermediary buffer , copy 1 data, add additional complexity.

i need in place, because data structures part of message have send server accepts input formatted way.

the message looks like:

  struct   {     char first_field   [6];     char second_field  [8];     char data_field    [12];   }; 

and might need set second_field before having set first one. have lot more fields fill in, generic solution appreciated. long can convert int string representation fine.

within indicated constraints may improve on own answer:

#include <algorithm> #include <cstddef> #include <cassert>  inline void  unsigned_to_decimal( unsigned long number, char* buffer, std::size_t size) {     std::size_t = size;     buffer[size - 1] = '0';     (unsigned long n ;(n = number) > 0 && > 0 ;) {         buffer[--i] = '0' + n - (10 * (number /= 10));     }     assert(number == 0);     std::fill(buffer,buffer + (i - (i == size)),' '); } 

for demo, append:

#include <iostream> #include <string> #include <climits> #include <array>  constexpr std::size_t decimal_digits(unsigned long n) {     return n / 10 > 0 ? 1 + decimal_digits(n / 10) : 1; }   int main() {     const std::size_t max_digits = decimal_digits(ulong_max);     std::cout << "print decimal 0, uint_max, ulong_max "         "from left-padded char buffer, size " << max_digits << ":-\n";      (auto ul : std::array<unsigned long,3>{0,uint_max,ulong_max}) {         char buf[max_digits];         std::fill(buf,buf + max_digits,'?');         std::cout << '[' << std::string(buf,buf + max_digits) << "]\n";         unsigned_to_decimal(ul,buf,max_digits);         std::cout << '[' << std::string(buf,buf + max_digits) << "]\n";     }     return 0; } 

which runs like:

print decimal 0, uint_max, ulong_max left-padded char buffer, size 20:- [????????????????????] [                   0] [????????????????????] [          4294967295] [????????????????????] [18446744073709551615] 

(g++ -wall -std=c++11 -pedantic, gcc 5.3.1)