当前位置:网站首页>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
边栏推荐
- Written by unity Jason
- Download blender on Alibaba cloud image station
- 配置基于接口的ARP表项限制和端口安全(限制用户私自接入傻瓜交换机或非法主机接入)
- Rock PI Development Notes (II): start with rock PI 4B plus (based on Ruixing micro rk3399) board and make system operation
- How to solve the failure of printer driver installation of computer equipment
- Trigger: MySQL implements adding or deleting a piece of data in one table and adding another table at the same time
- 只是巧合?苹果iOS16的神秘技术竟然与中国企业5年前产品一致!
- 学生选课系统(山东农业大学课程设计)
- AcWing 300. Task arrangement
- PCL 点云镜像变换
猜你喜欢
Yyds dry goods inventory has not revealed the artifact? Valentine's Day is coming. Please send her a special gift~
PWM breathing lamp
Penetration tool - intranet permission maintenance -cobalt strike
隐私计算技术创新及产业实践研讨会:学习
Multi task prompt learning: how to train a large language model?
电脑自带软件使图片底色变为透明(抠图白底)
DGraph: 大规模动态图数据集
Routing mode: hash and history mode
Notice on holding a salon for young editors of scientific and Technological Journals -- the abilities and promotion strategies that young editors should have in the new era
Take you ten days to easily complete the go micro service series (I)
随机推荐
Global and Chinese markets for airport baggage claim conveyors 2022-2028: technology, participants, trends, market size and share Research Report
关于举办科技期刊青年编辑沙龙——新时代青年编辑应具备的能力及提升策略的通知...
PCL point cloud image transformation
vscode设置删除行快捷键[通俗易懂]
Written by unity Jason
Leetcode1380: lucky numbers in matrix
只是巧合?苹果iOS16的神秘技术竟然与中国企业5年前产品一致!
路由模式:hash和history模式
渗透工具-内网权限维持-Cobalt strike
Global and Chinese market of switching valves 2022-2028: Research Report on technology, participants, trends, market size and share
pwm呼吸燈
你想要的宏基因组-微生物组知识全在这(2022.7)
Data security industry series Salon (III) | data security industry standard system construction theme Salon
Ranger (I) preliminary perception
Trigger: MySQL implements adding or deleting a piece of data in one table and adding another table at the same time
隐私计算技术创新及产业实践研讨会:学习
Detailed explanation of @accessories annotation of Lombok plug-in
Executive engine module of high performance data warehouse practice based on Impala
LeetCode 1. 两数之和
How to choose the right kubernetes storage plug-in? (09)