C/C++ snprintf() - Usage Guide With Examples

In this article, we’ll understand the working and the usage of the snprintf() C++ function.

The snprintf() function is used to write formatted output to a string. Let’s understand how we can use this function, by showing it’s syntax and giving examples.

Basic Syntax of snprintf() in C/C++

Since the snprintf() function will write to a string buffer, it takes a string as an argument, and also a formatted string.

A formatted string is any string that contains format specifiers, like %d, %c or %s. This is similar to printf() or cout, except that it will write to a string instead.

The basic function signature is the following:

Here, buffer is the string buffer that we will write to, with a maximum capacity of buf_size. format is the format string, that we will write to the buffer.

NOTE: The buffer is an array of characters (char*), and not a string. This is because this is a C compatible function, and C does not have the string class.

If the execution is successful, it will return the number of characters written, if there is no problem in writing. Otherwise, it will return a negative integer.

If the buffer size is too small, the input string will be truncated to the buffer size.

Similar to printf(), this is a library function defined in <stdio.h>

Let’s now take a look at some examples of this function.

Using snprintf() in C/C++

We’ll take a format string containing some integers and strings, and write it to a buffer.

Let’s assume a format string of the form:

We’ll now write it to a buffer, using snprintf().


As you can see, our buffer was indeed updated with our format string contents!

Let’s take another case when you’re trying to write a string that is too large for our buffer. Here, let’s take a small buffer size of 20, and try to see what happens.


Even though we’ve read the same number of characters as before (34), since our buffer size is not big enough, the format string is reduced to the buffer size.

So, our output only has 20 characters, the same as the size of the buffer.


Hopefully, you’ve now understood how you can use the snprintf() function. This is similar to printf(), with the difference being that you write to a string buffer, instead of stdout.

For similar articles on C++, do go through our list of C++ articles.


By admin

Leave a Reply

%d bloggers like this: