Detailed explanation and usage of the sprintf function in C language.
sprintf function is a string handling function in C language, which is used to write formatted data into a string.
The prototype of the sprintf function is as follows:
int sprintf(char *str, const char *format, ...);
str is a pointer to a character array used to store the formatted string; format is a format string used to specify the output format; … represents variable parameters used to specify the data to be formatted.
The sprintf function converts variable arguments into a string based on the formatting control symbols in the format string, and stores the result in the character array pointed to by str.
Below are some commonly used formatting control characters and their corresponding conversion specifications:
- %d: Output the integer in decimal format.
- %f: display the floating point number in decimal format.
- %c: Displaying characters based on their ASCII codes.
- %s: prints the string.
- Output a percentage sign.
Here is a sample code demonstrating the usage of the sprintf function:
#include <stdio.h>
int main()
{
char str[100];
int num = 123;
float fnum = 3.14;
char ch = 'A';
char name[] = "Tom";
sprintf(str, "num = %d, fnum = %f, ch = %c, name = %s", num, fnum, ch, name);
printf("%s\n", str);
return 0;
}
Execution result:
num = 123, fnum = 3.140000, ch = A, name = Tom
In the above code, the sprintf function formats integers, floating point numbers, characters, and strings into one string, and stores it in the str array. The printf function then prints out this string.
It’s important to note that the sprintf function does not check the length of the target string. If the formatted string exceeds the length of the target string, it could cause a buffer overflow. To prevent this, you can use the snprintf function, which takes an extra parameter to specify the length of the target string. For example:
snprintf(str, sizeof(str), "num = %d, fnum = %f, ch = %c, name = %s", num, fnum, ch, name);