C++ std::snprintf
Format into a bounded character array and check how much space the full text would require.
A simple example
std::snprintf
- Start with "AB" and room for 3 bytes
- Do this Format a C string
- Result 2 visible characters
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
./lessonCheck 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.
#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;
}
Use a larger label
PK-482 takes six visible characters and needs a seventh byte for the terminator. The return value exposes the truncation.
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?
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?
What to watch for
Check for a negative return before comparing the required length with the buffer size.