Library contents

C++ std::snprintf

Format into a bounded character array and check how much space the full text would require.

A simple example

std::snprintf

  1. Start with "AB" and room for 3 bytes
  2. Do this Format a C string
  3. Result 2 visible characters
The buffer holds A, B and the terminating zero. The reported text length excludes the terminator.

Syntax

C++ syntax
std::snprintf(label, sizeof label, "PK-%d", 482)
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Check whether a parcel label fits a buffer

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.

ResultUse a larger label
lesson.cpp
#include <cstdio>

int main() {
    char label[5];
    int needed = std::snprintf(label, sizeof label, "PK-%d", 482);
    if (needed < 0) return 1;
    std::puts(static_cast<std::size_t>(needed) >= sizeof label ? "Use a larger label" : label);
    return 0;
}
Output
Use a larger label

PK-482 takes six visible characters and needs a seventh byte for the terminator. The return value exposes the truncation.

Advertisements

Size a sample-label buffer

A lab printer needs to store a four-character code. Include room for a terminating zero byte when sizing this ASCII label buffer. How many bytes does the complete string require?

GivenLAB7 + terminator
Worked result5

Size a parcel label buffer

A courier printer holds the identifier as a C-style string. Include room for a terminating zero byte when sizing this ASCII label buffer. How many bytes does the complete string require?

GivenP-104 + terminator
Worked result6

What to watch for

Check for a negative return before comparing the required length with the buffer size.

Documentation for std::snprintf