A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/c_standard_library/c_function_sprintf.htm below:

C Library - sprintf() function

C Library - sprintf() function

The C Library sprintf() function allows you to create strings with specified formats, similar to printf(), but instead of printing to the standard output, it stores the resulting string in a character array provided by the user.

Syntax

Following is the C library syntax of the sprintf() function −

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

This function accepts the following parameters −

Return Value

The sprintf() function returns the number of characters written to the string str, excluding the null-terminating character.

Example 1: Formatting Floating Point Numbers

Here, sprintf() formats a floating-point number with two decimal places.

Below is the illustration of the C library sprintf() function.

#include <stdio.h>

int main() {
    char buffer[100];
    float pi = 3.14159;
    sprintf(buffer, "The value of pi is %.2f.", pi);
    printf("%s\n", buffer);
    return 0;
}
Output

The above code produces following result−

The value of pi is 3.14.
Example 2: Combining Strings and Integers

This example showcases how sprintf() can combine strings and integers into a single formatted string.

#include <stdio.h>

int main() {
    char buffer[100];
    int age = 30;
    char name[] = "John";
    sprintf(buffer, "%s is %d years old.", name, age);
    printf("%s\n", buffer);
    return 0;
}
Output

After execution of above code, we get the following result

John is 30 years old.

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4