Using the sprintf() function in C/C++

Filed Under: C Programming
Sprintf C Cpp

In this article, we’ll take a look at using the sprintf() function in C / C++.

This is an important function if you want to write characters from a format string into a buffer.

Let’s take a look at this function, using illustrative examples!


Basic Syntax of the sprintf() function in C/C++

This function takes a format string and writes it into a string buffer.

This is very similar to printf(), but writes the output to a buffer instead of stdout.

This is function is present in the <stdio.h> header file.

#include <stdio.h>

int sprintf (char* buffer, const char* fmt, ...);

Here, this takes in an input fmt string along with necessary arguments (denoted by ...) and stores it into buffer.

The function returns the number of characters written to the buffer if it succeeds.

If it fails, it will return a negative integer.

The size of the buffer must be large enough to accomodate the string! Otherwise, you can access an unbound memory location.

Now, to understand this completely, let’s look at some examples:


Using sprintf() – Some Examples

Let’s take an input from the user, and concatenate it onto a string, using sprintf().

#include <stdio.h>

int main() {
    char original[] = "Hello from JournalDev";

    char buffer[256];

    printf("Enter an integer:\n");

    int n;
    scanf("%d", &n);

    sprintf(buffer, "%s_%d", original, n);

    printf("Buffer = %s\n", buffer);

    return 0;
}

Output

Enter an integer:
100
Buffer = Hello from JournalDev_100

As you can see, we used the format string to concatenate an integer to a string directly.

You may just realize how handy this function can be when used at the right time!

Let’s now take another example to verify that all the characters are written to the buffer.

#include <stdio.h>

int main() {
    char original[] = "Hello from JournalDev";

    char buffer[25];

    printf("Enter an integer:\n");

    int n;
    scanf("%d", &n);

    int num_written = sprintf(buffer, "%s_%d", original, n);

    printf("Buffer = %s\n", buffer);

    printf("Number of Characters written using sprintf() = %d\n", num_written);

    return 0;
}

Output

Enter an integer:
10
Buffer = Hello from JournalDev_10
Number of Characters written using sprintf() = 24

As you can see, the number of characters written (24), is the same as the string length!


Conclusion

In this article, we learned about using the sprintf() function in C/C++. This is useful if you want to write to a string using a format specifier.

For similar content, do go through our tutorial section on C programming, which covers various aspects of C and C++.

References


Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages