sprintf() in C - Source Code Example

In this source code example, we will see how to use the sprintf() function in C programming with an example.

Function Overview

The sprintf() function is found in the C library <stdio.h>. It lets you make a string from different types of data, like numbers or other strings. Instead of showing the result on the screen like printf(), sprintf() saves the result in a buffer or a string.

Source Code Example

#include <stdio.h>

int main() {
    char buffer[100];  // A place to save our new string

    // Using a number in a string
    int age = 30;
    sprintf(buffer, "Ram is %d years old.", age);
    printf("%s\n", buffer);

    // Making a string from a number and another string
    char hobby[] = "painting";
    double hours = 3.5;
    sprintf(buffer, "Ram spends %.1lf hours every day on %s.", hours, hobby);
    printf("%s\n", buffer);

    // Making a string from three strings
    char subject[] = "C programming";
    char verb[] = "is";
    char adjective[] = "fun";
    sprintf(buffer, "For Ram, %s %s %s.", subject, verb, adjective);
    printf("%s\n", buffer);

    return 0;
}

Output

Ram is 30 years old.
Ram spends 3.5 hours every day on painting.
For Ram, C programming is fun.

Explanation

Here's what the code does:

1. It shows how to use sprintf() to add a number to a string.

2. It shows how you can mix different things like numbers and strings to make a new string.

3. It shows how to make a string by joining three other strings together.

This shows how handy sprintf() can be when you want to make new strings in C.


Comments