sprintf Formatting in C

Level 4178 keystrokes

Uses sprintf to format a date string into a buffer with zero padding.

C code

// Buffer to hold formatted string
1char buffer[50];
// Date components
2int day = 15, month = 8, year = 2024;
// sprintf writes to buffer instead of stdout
// %04d pads the year to 4 digits, %02d pads to 2 (8 becomes 08)
3sprintf(buffer, "%04d-%02d-%02d", year, month, day);
// Prints Date: 2024-08-15
4printf("Date: %s\n", buffer);
// strlen counts the characters before '\0': 10 (it returns size_t; %zu is the exact specifier)
5printf("Length: %lu\n", strlen(buffer));

Output

Date: 2024-08-15
Length: 10
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ,× 8
  • "× 6
  • ;× 5
  • %× 5
  • (× 4
  • )× 4
  • =× 3
  • -× 2
  • :× 2
  • \× 2

More C examples at level 4

← C typing practice