The sprintf() Function in C

The sprintf() works just like printf() but instead of sending output to console it returns the formatted string.

Syntax: int sprintf(char *str, const char *control_string, [ arg_1, arg_2, ... ]);

The first argument to sprintf() function is a pointer to the target string. The rest of the arguments are the same as for printf() function.

The function writes the data in the string pointed to by str and returns the number of characters written to str, excluding the null character. The return value is generally discarded. If an error occurs during the operation it returns -1.

The following program demonstrates how to use sprintf() function.

#include<stdio.h>
#include<string.h>
int factorial(int );

int main()
{

    int sal;
    char name[30], designation[30], info[60];

    printf("Enter your name: ");
    gets(name);

    printf("Enter your designation: ");
    gets(designation);

    printf("Enter your salary: ");
    scanf("%d", &sal);

    sprintf(info, "Welcome %s !\nName: %s \nDesignation: %s\nSalary: %d",
        name, name, designation, sal);

    printf("\n%s", info);

    // signal to operating system program ran fine
    return 0;
}

Expected Output:

Enter your name: Sim
Enter your designation: Developer
Enter your salary: 230000

Welcome Sim !
Name: Sim
Designation: Developer
Salary: 230000

Another important use of sprintf() function is to convert integer and float values to strings.

#include<stdio.h>
#include<string.h>
int factorial(int );

int main()
{
    char s1[20];
    char s2[20];

    int x = 100;
    float y = 300;

    sprintf(s1, "%d", x);
    sprintf(s2, "%f", y);

    printf("s1 = %s\n", s1);
    printf("s2 = %s\n", s2);

    // signal to operating system program ran fine
    return 0;
}

Expected Output:

s1 = 100
s2 = 300.000000