When writing code, we often encounter type conversion, which can be quite troublesome. However, today I discovered a very interesting function while reviewing solutions: sprintf and sscanf. (These can also be used in C language.)You will notice that the names of these two functions are quite similar to printf and scanf. The sprintf function prints to a string, while the printf function outputs to the screen. The sprintf function is widely used for converting other data types into string types. (It is important to ensure that the string length is sufficient to hold the printed content; otherwise, memory overflow may occur).In simple terms, it means printing a bunch of things into a string.Regardless of whether you understand it or not, let’s jump straight to the examples:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
int main() {
printf("=== C language sprintf() function usage demonstration ===\n\n");
printf("1. Basic usage demonstration\n");
printf("================\n");
char str[100];
int num = 123;
sprintf(str, "Number is: %d", num);
printf("sprintf result: %s\n", str);
printf("Explanation: sprintf writes the formatted string to the character array instead of outputting it to the screen\n");
printf("\n2. Precision control demonstration\n");
printf("================\n");
char str[20];
double f = 14.309948;
sprintf(str, "%6.2f", f);
printf("Original value: %.6f\n", f);
printf("Formatted result: '%s'\n", str);
printf("Explanation: %%6.2f indicates a total width of 6 characters, with 2 decimal places\n");
printf("\n3. Multiple values concatenation demonstration\n");
printf("==================\n");
char str[30];
int a = 20984, b = 48090;
sprintf(str, "%3d%6d", a, b);
printf("Value a: %d, Value b: %d\n", a, b);
printf("Concatenation result: '%s'\n", str);
printf("Explanation: %%3d%%6d concatenates two integers with specified widths\n");
printf("\n4. String concatenation demonstration\n");
printf("================\n");
char str[20];
char s1[5] = {'A', 'B', 'C', '\0'};
char s2[5] = {'T', 'Y', 'X', '\0'};
sprintf(str, "%.3s%.3s", s1, s2);
printf("String s1: %s\n", s1);
printf("String s2: %s\n", s2);
printf("Concatenation result: %s\n", str);
printf("Explanation: %%.3s%%.3s concatenates two strings, taking at most 3 characters from each\n");
return 0;
}
You can copy the code and study it yourself; now I will explain it in detail.Here, I will explain using sprintf, and sscanf is similar.sprintf(you need to specify the string, “the format is the same as in printf, such as %d%d, etc.”, a, b, c, d…)In simpler terms, the first argument is the name of the string where you want to place the content, and the rest follows the normal printf format.For example:
int a,b;
printf("%d%d",a,b);// This is the output format
string s;
sprintf(s,"%d%d",a,b);// This is the sprintf format
sprintf allows you to write any type into a string, eliminating the hassle of type conversion.sscanf is quite similar to this.