The sprintf()
function in C is used to format and store a string in a buffer (array of characters) according to a specified format. It works similarly to printf()
, but instead of printing the output to the console, it stores the formatted result in a string.
Syntax:
int sprintf(char *str, const char *format, ...);
str
: A pointer to the character array where the formatted string will be stored.format
: A format string that specifies how subsequent arguments (if any) should be formatted....
: A list of variables or values to be formatted according to the format string.
Return Value:
sprintf()
returns the number of characters written (excluding the null terminator) to the stringstr
. If an error occurs, it returns a negative value.
Example:
#include <stdio.h>
int main() {
char buffer[100];
int x = 42;
float y = 3.14159;
// Use sprintf to format and store the output in buffer
int length = sprintf(buffer, "The value of x is %d and the value of y is %.2f", x, y);
// Print the formatted string
printf("Formatted string: %s\n", buffer);
printf("Number of characters written: %d\n", length);
return 0;
}
Explanation:
- The
sprintf()
function formats the string"The value of x is 42 and the value of y is 3.14"
, storing it in thebuffer
array. %d
is used to format the integerx
, and%.2f
is used to format the floaty
with two decimal places.- The return value,
length
, contains the number of characters written into the buffer (excluding the null-terminator).
Output:
Formatted string: The value of x is 42 and the value of y is 3.14
Number of characters written: 53
Notes:
- Buffer Size: It’s important to ensure the buffer is large enough to hold the formatted string to avoid buffer overflows.
- Security Warning:
sprintf()
does not check the size of the destination buffer. For safer string formatting, consider usingsnprintf()
, which allows you to specify the buffer size to prevent overflows.
Example with snprintf
for safety:
#include <stdio.h>
int main() {
char buffer[100];
int x = 42;
float y = 3.14159;
// Use snprintf to format safely with buffer size limit
int length = snprintf(buffer, sizeof(buffer), "The value of x is %d and the value of y is %.2f", x, y);
printf("Formatted string: %s\n", buffer);
printf("Number of characters written: %d\n", length);
return 0;
}
This ensures that the string fits within the specified buffer
size, avoiding potential overflows.