Boost C++ Libraries of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.


Header <boost/core/snprintf.hpp>


  • Andrey Semashev

The header <boost/core/snprintf.hpp> provides portable definition of snprintf, vsnprintf and their corresponding wchar_t counterparts. On a platform that supports these functions in the standard library, these definitions are equivalent to the standard functions. On other platforms (mainly, older MSVC versions) these functions are emulated through non-standard functions that have similar behavior.

Depending on the standard library, certain implementation differences are exposed to the user:

  • Any non-standard behavior with respect to string format description are not hidden by the emulation.
  • Returned value of boost::core::snprintf in case if the output buffer is too small may not be equal to the number of characters that would have been written if the buffer was large enough. It is, however, equal or larger than the buffer size, which still allows the caller to detect the buffer overflow condition. The formatted output is still properly null-terminated in this case.
[Note] Note

Unlike snprintf, swprintf does not return the number of characters to be written if the output buffer is too small but returns -1 instead. Furthermore, swprintf may or may not produce characters in the output buffer in this case.

char buf[10];
int n = boost::core::snprintf(buf, sizeof(buf), "%d", i);
if (n < 0)
    throw std::runtime_error("Formatting error");
if (n >= sizeof(buf))
    throw std::runtime_error("Formatting buffer overflow");