sprintf() function in C++

In this guide, you will learn what is sprintf() function is in C++ programming and how to use it with an example.

1. sprintf() Function Overview

The sprintf() function is a part of the <cstdio> library in C++. It is used to format and store a series of characters and values in the char array pointed by str. This function behaves similarly to the printf() function, but rather than sending the formatted string to standard output, it saves it in the specified character array.

Signature:

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

Parameters:

- str: Pointer to the destination char array, where the resulting C-string is stored.

- format: A string that contains text and format specifiers, which define the expected data types for the subsequent arguments.

- ...: Variable number of arguments to be formatted and inserted in the resulting string.

2. Source Code Example

#include <iostream>
#include <cstdio>

int main() {
    int age = 25;
    char name[] = "JohnDoe";
    char result[100];

    // Format and store in result
    sprintf(result, "Name: %s\nAge: %d", name, age);

    // Print the result
    std::cout << result << std::endl;

    return 0;
}

Output:

Name: JohnDoe
Age: 25

3. Explanation

1. We define an integer age, a character array name to store the given values, and a character array result to store the output of the sprintf() function.

2. The sprintf() function formats the string based on the format specifiers provided and stores the resultant string in the result array.

3. Finally, the result is printed using std::cout.

Note: Care should be taken to ensure that the formatted string does not exceed the size of the destination character array to avoid buffer overflows.


Comments