Library contents

C snprintf

Write a formatted label into a bounded character array and inspect the required size.

A simple example

snprintf

  1. Start with Text A, template [value]
  2. Do this Insert text between brackets
  3. Result "[A]"
Formatting keeps the brackets and fills the single space reserved for a value.

Syntax

C 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
./lesson

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

ResultQ-007
lesson.c
#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;
}
Output
Q-007

The buffer has room for the characters and their terminating null.

Advertisements

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.

ResultToo long
lesson.c
#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;
}
Output
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?

GivenPrefix “Ticket ” + 1
Worked resultTicket 1

What to watch for

The return value excludes the terminator. Handle negative results and truncation before using the output.

Documentation for snprintf