Printing Formatted Strings with sprintf in C programming
sprintf in CPrinting Formatted Strings with sprintf in C
The sprintf function in C is used to format and store a string in a character array. It is similar to printf, but instead of printing the formatted string to the standard output, it stores the formatted string in a buffer.
Syntax
The syntax for sprintf is as follows:
int sprintf(char *str, const char *format, ...);
Where:
stris a pointer to the character array where the formatted string will be stored.formatis the format string that specifies how subsequent arguments are formatted....represents the additional arguments that are formatted according to theformatstring.
Example Code
#include <stdio.h>
int main() {
char buffer[100];
int age = 30;
double height = 1.75;
sprintf(buffer, "Age: %d years\nHeight: %.2f meters", age, height);
printf("Formatted String:\n%s\n", buffer);
return 0;
}
In this example:
char buffer[100];declares a character array to store the formatted string.int age = 30;anddouble height = 1.75;are variables to be included in the formatted string.sprintf(buffer, "Age: %d years\nHeight: %.2f meters", age, height);formats the string and stores it inbuffer.printf("Formatted String:\n%s\n", buffer);prints the contents ofbufferto the standard output.
Key Points
- Buffer Size: Ensure the buffer size is sufficient to hold the formatted string and the null terminator.
- Return Value:
sprintfreturns the number of characters written to the buffer, excluding the null terminator. - Formatting: Use format specifiers to control how different types of data are represented in the formatted string.
Note: Unlike
printf, sprintf does not output to the console but rather to a string buffer, making it useful for preparing strings for later use.
Comments
Post a Comment