当前位置:网站首页>Usage of sprintf() function in C language
Usage of sprintf() function in C language
2022-07-02 16:56:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
sprintf Function usage
1、 This function is contained in stdio.h In the header file . 2、sprintf In peace, we often use printf The functions are very similar .sprintf Function to print to a string ( Note that the length of the string should be enough to accommodate the printed content , Otherwise, there will be a memory overflow ), and printf Function prints out to the screen .sprintf Function is widely used in our operation of converting other data types into string types . 3、sprintf Format of function : int sprintf( char *buffer, const char *format [, argument,…] ); Except that the first two parameters are fixed , Optional parameters can be any number of .buffer Is the character array name ;format It's a formatted string ( image :”%3d%6.2f%#x%o”,% And # When used together , Automatically precede hexadecimal numbers with 0x). As long as printf Format string that can be used in , stay sprintf You can use . The format string is the essence of this function . printf and sprintf Both use a formatted string to specify the format of the string , Inside the format string, use some to ”%” Format specifier at the beginning to occupy a position , Provide the corresponding variables in the following variable parameter list , In the end, the function will replace the specifier with a variable in the corresponding position , Generate a string that the caller wants . 4、 Can control the accuracy char str[20]; double f=14.309948; sprintf(str,”%6.2f”,f); 5、 You can connect multiple numerical data char str[20]; int a=20984,b=48090; sprintf(str,”%3d%6d”,a,b); str[]=”20984 48090” 6、 You can connect multiple strings into a string char str[20]; char s1[5]={‘A’,’B’,’C’}; char s2[5]={‘T’,’Y’,’x’}; sprintf(str,”%.3s%.3s”,s1,s2); %m.n In the output of the string ,m Width , The number of columns shared by strings ;n Represents the actual number of characters .%m.n In floating point numbers ,m Also means width ;n Represents the number of decimal places . 7、 You can dynamically specify , The number of characters to be intercepted char str[20]; char s1[5]={‘A’,’B’,’C’}; char s2[5]={‘T’,’Y’,’x’}; sprintf(str,”%.*s%.*s”,2,s1,3,s2); sprintf(str, “%*.*f”, 10, 2, 3.1415926); 8、 You can print it out i The address of char str[20]; int i; sprintf(str, “%p”, &i); The above statement is equivalent to sprintf(str, “%0*x”, 2 * sizeof(void *), &i); 9、sprintf The return value of is the number of characters in the character array , The length of the string , No need to call strlen(str) Find the length of the string . 10、 Use the string pointed by the character pointer to receive the printed content Example :
int main()
{
int ddd=666;
char *buffer=NULL;
if((buffer = (char *)malloc(80*sizeof(char)))==NULL)
{
printf("malloc error\n");
}
sprintf(buffer, "The value of ddd = %d", ddd);//The value of ddd = 666
printf("%s\n",buffer);
free(buffer);
buffer=NULL;
return 0;
}When the pointer was first defined , Does not point to where , Can point to a variable , And then you can use , If you want to simply use this pointer , Then give this pointer malloc Allocate a piece of memory , added malloc Just add stdlib.h 11、 Imagine when you take a record out of a database , Then you want to join their fields into a string according to some rules , You can use this method , In theory , He should be better than strcat Efficient , because strcat Each call needs to find the last string end character first ’\0 The location of , And in the example given above , We use it every time sprintf The return value records the location directly . Example :
void main(void)
{
char buffer[200], s[] = "computer", c = 'l';
int i = 35, j;
float fp = 1.7320534f; //
j = sprintf( buffer, " String: %s\n", s ); //
j += sprintf( buffer + j, " Character: %c\n", c ); //
j += sprintf( buffer + j, " Integer: %d\n", i ); //
j += sprintf( buffer + j, " Real: %f\n", fp );//
printf( "Output:\n%s\ncharacter count = %d\n", buffer, j );
}This example is to connect all the defined data with the characters in the format control block , Finally print it out buffer And the number of characters in the string . The result is shown in the figure :
12、 Format numeric strings sprintf One of the most common applications is to print integers into strings . Such as : (1) Integer 123 Print it as a string and save it in s in . sprintf(s, “%d”, 123); // produce “123″ (2) You can specify the width , Fill in the blanks on the left side of the deficiency : sprintf(s, “%8d%8d”, 123, 4567); // produce :“ 123 4567″ Of course, it can also be left aligned : sprintf(s, “%-8d%8d”, 123, 4567); // produce :“123 4567″ (3) You can also follow 16 Binary printing : sprintf(s, “%8x”, 4567); // A lowercase letter 16 Base number , Width share 8 A place , Right alignment sprintf(s, “%-8X”, 4568); // Capitalization 16 Base number , Width share 8 A place , Align left such , An integer 16 The binary string is easy to get , But we're printing 16 When the content is decimal , I usually want a left complement 0 The same width format of , What should I do ? It's simple , Add... Before the number for width 0 That's all right. . sprintf(s, “%08X”, 4567); // produce :“000011D7″ On top of it ”%d” On going 10 This left complement can also be used in decimal printing 0 The way . Here we should pay attention to the problem of symbol extension : such as , If we want to print short integers (4)(short)-1 Of memory 16 The hexadecimal representation , stay Win32 On the platform , One short Type occupation 2 Bytes , So naturally we want to use 4 individual 16 Print it in decimal digits : short si = -1; sprintf(s, “%04X”, si); produce “FFFFFFFF, What's going on? ? because sprintf It's a variable parameter function , In addition to the first two parameters , The following parameters are not type safe , There's no way for a function to pass through just one “%X” You can know when the parameters were pressed on the stack before the function call What is being pushed in 4 An integer of bytes is still 2 Short integer in bytes , So we took a unified approach 4 How bytes are handled , The symbol extension is made when the parameter stack is pressed , Expanded to 32 An integer -1, When printing 4 It's not enough , Just put 32 An integer -1 Of 8 position 16 It's all printed out . If you want to see si As it is , So let the compiler do 0 Extension, not symbolic extension ( When expanding, the binary left complement 0 Instead of complementing the sign bit ): sprintf(s, “%04X”, (unsigned short)si); That's all right. . perhaps : unsigned short si = -1; sprintf(s, “%04X”, si); sprintf and printf You can also press 8 Decimal print integer string , Use ”%o”. Be careful 8 Into the system and 16 It doesn't print negative numbers , It's all signed , In fact, it is the direct use of internal coding of variables 16 Base or 8 Hexadecimal said .
Reference resources :http://blog.csdn.net/cos_sin_tan/article/details/7548632http://nnssll.blog.51cto.com/902724/198237/http://blog.csdn.net/s202090414/article/details/8690518http://blog.csdn.net/peng___peng/article/details/51510685
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/147848.html Link to the original text :https://javaforall.cn
边栏推荐
- PCL 最小中值平方法拟合平面
- Trigger: MySQL implements adding or deleting a piece of data in one table and adding another table at the same time
- vscode设置删除行快捷键[通俗易懂]
- 基于多元时间序列对高考预测分析案例
- LeetCode 4. Find the median (hard) of two positive arrays
- 2322. 从树中删除边的最小分数(异或和&模拟)
- P6774 [noi2020] tears in the era (block)
- OpenHarmony如何启动远程设备的FA
- pwm呼吸燈
- 隐私计算技术创新及产业实践研讨会:学习
猜你喜欢

Résumé de l'entrevue de Dachang Daquan

Go zero micro service practical series (VIII. How to handle tens of thousands of order requests per second)

pwm呼吸燈

Yolov5 practice: teach object detection by hand

Yyds dry goods inventory # look up at the sky | talk about the way and principle of capturing packets on the mobile terminal and how to prevent mitm

Multi task prompt learning: how to train a large language model?

LeetCode 2. Add two numbers

How openharmony starts FA of remote devices

How to solve the failure of printer driver installation of computer equipment

Yyds dry inventory uses thread safe two-way linked list to realize simple LRU cache simulation
随机推荐
渗透工具-内网权限维持-Cobalt strike
上传代码到远程仓库报错error: remote origin already exists.
数字IC手撕代码--投票表决器
Classic quotations
Leetcode1380: lucky numbers in matrix
Global and Chinese markets for carbon dioxide laser cutting heads 2022-2028: Research Report on technology, participants, trends, market size and share
[error record] error -32000 received from application: there are no running service protocol
Easy language ABCD sort
Cloud native cicd framework: Tekton
pwm呼吸燈
Day 18 of leetcode dynamic planning introduction
TCP server communication process (important)
Interview summary of large factories
Global and Chinese market of oil analyzers 2022-2028: Research Report on technology, participants, trends, market size and share
亚马逊云科技 Community Builder 申请窗口开启
lsf基础命令
Analysis of how to prevent virus in industrial computer
Cell: Tsinghua Chenggong group revealed an odor of skin flora. Volatiles promote flavivirus to infect the host and attract mosquitoes
618深度複盤:海爾智家的制勝方法論
jsp 和 servlet 有什么区别?