OverIQ.com

The sprintf() Function in C

Last updated on July 27, 2020


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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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:

1
2
3
4
5
6
7
8
Enter your name: Bob
Enter your designation: Developer
Enter your salary: 230000

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

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#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:

1
2
s1 = 100
s2 = 300.000000