C sprintf() Function Tutorial

In this section we will learn what the sprintf() function is and how to use it in C.

C Format String: sprintf() Function

The `sprintf` function is declared in the `stdio.h` header file and it works like the `printf` function. But it writes to a string instead of writing to the output stream. Therefore, it provides a way to combine several elements into a single string.

sprintf() Function Syntax

int sprintf(char *str, const char *format, ...)

sprintf() Function Parameters

The first argument to `sprintf` function is the address of the target string.

The remaining arguments are the same as for `printf` function. Basically, we can put format specifiers as the second argument of the function and then replace them by adding more arguments to the function.

Note: Check the printf() section if you’re not familiar with this function as well as format specifiers.

sprintf() Function Return Value

If the operation of calling the sprintf() function succeeded, then the total number of characters that was written to the target string variable will return as a result.

Note: the null character at the end of string values is not counted.

Example: sprintf() in C

#include <stdio.h>

int main() {

    char destination[100] ;
    int age = 28;
    sprintf(destination,"The age is: %d",age);

    puts(destination);

    return  0;
}

Output:

The age is: 28
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies