C snprintf
Write a formatted label into a bounded character array and inspect the required size.
A simple example
snprintf
- Start with Text A, template [value]
- Do this Insert text between brackets
- Result "[A]"
Syntax
snprintf(tag, sizeof tag, "Q-%03d", number)
Run these examples in C
Save one example at a time as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonPrint a queue ticket
A printer receives badge or ticket data in separate fields. Use the display format required by the desk so names, numbers and separators occupy their intended places on the finished label.
#include <stdio.h>
int main(void) {
char tag[16];
int count = snprintf(tag, sizeof tag, "Q-%03d", 7);
if (count < 0 || (size_t)count >= sizeof tag) return 1;
puts(tag);
return 0;
}
Q-007
The buffer has room for the characters and their terminating null.
Detect a shortened badge
A printer or scanner accepts a fixed-width field. Compare the space required by the label with the capacity of the destination so a shortened field cannot pass unnoticed.
#include <stdio.h>
int main(void) {
char tag[4];
int count = snprintf(tag, sizeof tag, "%s", "Campus");
if (count < 0) return 1;
puts((size_t)count >= sizeof tag ? "Too long" : tag);
return 0;
}
Too long
The required character count excludes the terminator. Checking it exposes truncation.
Print the first entry tag
A coat-check desk numbers the first ticket one. The ticket printer includes the number as ordinary decimal text after a prefix. What does the completed label say?
What to watch for
The return value excludes the terminator. Handle negative results and truncation before using the output.