0

I am looking for a way to convert an int to a string of a given length. If the representation of the number is shorter, it should be zero-filled.

I.e., what I'd like to see:

snprintf(buffer, 3, "%d", 5); -> 005
snprintf(buffer, 2, "%d", 55); -> 55

Actually, snprintf(buffer, 3, "%d", 5); just return 5 in string.

Is there a simple way to do this ?

Lars Noschinski
  • 3,667
  • 16
  • 29
Droïdeka
  • 47
  • 6
  • 1
    Many answsers here http://stackoverflow.com/questions/9655202/how-to-convert-integer-to-string-in-c – Dimitri Sep 11 '14 at 16:33

3 Answers3

2

You are looking for the "field width specifier"

char buffer[10];
snprintf(buffer, sizeof(buffer), "%d", 5); -> "5"
snprintf(buffer, sizeof(buffer), "%3d", 5); -> "  5"
snprintf(buffer, sizeof(buffer), "%03d", 5); -> "005"
snprintf(buffer, sizeof(buffer), "%2d", 55); -> "55"
snprintf(buffer, sizeof(buffer), "%3d", 55); -> " 55"
snprintf(buffer, sizeof(buffer), "%03d", 55); -> "055"

The second argument to snprintf() is the maximum number of bytes to store in buffer. This protects you from buffer overruns, which the older sprintf() (no 'n') is susceptible to.

Colin D Bennett
  • 11,294
  • 5
  • 49
  • 66
  • 1
    Important note: this assumes that `buffer` is array. If it is pointer to buffer, this will not work, `sizeof` will give size of pointer (usually 4 or 8) and not size of whatever it points to. – hyde Sep 11 '14 at 16:36
  • Good point, nasty pointers. – Colin D Bennett Sep 11 '14 at 16:38
1

The second argument of snprintf specifies a msximum length. If you want to always display a certain number of digits, and pad the leading edge with zeroes, you can specify that in the format specifier.

sprintf(buffer, "%03d", 5); // will output "005"

Specifying a number before the format specifier declares a fixed length. Simply specifying a number will pad the length out with spaces, but we can pad it with zeroes by including a leading zero in the specifier.

Edit: as pointed out in the comments, using snprintf is still a good idea, in case buffer hasn't been allocated enough space. Just remember that you'll need to pass the length of the string + 1 as the second argument for snprintf.

Woodrow Barlow
  • 8,477
  • 3
  • 48
  • 86
  • It's still prudent to use `snprintf` and not `sprintf` to avoid accidental buffer overflows. – hyde Sep 11 '14 at 16:35
0

There are all kinds of qualifiers on printf format strings. Check out http://www.cprogramming.com/tutorial/printf-format-strings.html

The one that is useful in this case is "%03d", although you'll need to snprintf 4 characters (3 plus the null terminator) to correctly get 005 out of that.

Vicky
  • 12,934
  • 4
  • 46
  • 54
KC-NH
  • 748
  • 3
  • 6
  • 2
    Could you explain which of the modifiers the OP needs to use to solve his problem? RTFM isn't a particularly helpful answer. – Philip Kendall Sep 11 '14 at 16:33