当前位置:网站首页>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
边栏推荐
- 七一献礼:易鲸捷 “百日会战”完美收官 贵阳银行数据库提前封板
- Configure ARP table entry restrictions and port security based on the interface (restrict users' private access to fool switches or illegal host access)
- Yyds dry goods inventory has not revealed the artifact? Valentine's Day is coming. Please send her a special gift~
- 【云原生】简单谈谈海量数据采集组件Flume的理解
- Global and Chinese market of oil analyzers 2022-2028: Research Report on technology, participants, trends, market size and share
- C语言中sprintf()函数的用法
- [North Asia data recovery] data recovery case of raid crash caused by hard disk disconnection during data synchronization of hot spare disk of RAID5 disk array
- Global and Chinese markets for slotting milling machines 2022-2028: Research Report on technology, participants, trends, market size and share
- Global and Chinese markets for carbon dioxide laser cutting heads 2022-2028: Research Report on technology, participants, trends, market size and share
- LeetCode 4. Find the median (hard) of two positive arrays
猜你喜欢
Masa framework - DDD design (1)
亚马逊云科技 Community Builder 申请窗口开启
关于举办科技期刊青年编辑沙龙——新时代青年编辑应具备的能力及提升策略的通知...
Trigger: MySQL implements adding or deleting a piece of data in one table and adding another table at the same time
【云原生】简单谈谈海量数据采集组件Flume的理解
Download blender on Alibaba cloud image station
基于多元时间序列对高考预测分析案例
Interview summary of large factories
In MySQL and Oracle, the boundary and range of between and precautions when querying the date
john爆破出現Using default input encoding: UTF-8 Loaded 1 password hash (bcrypt [Blowfish 32/64 X3])
随机推荐
Global and Chinese markets of stainless steel surgical suture 2022-2028: Research Report on technology, participants, trends, market size and share
基于多元时间序列对高考预测分析案例
电脑自带软件使图片底色变为透明(抠图白底)
寒门再出贵子:江西穷县考出了省状元,做对了什么?
Configure MySQL under Linux to authorize a user to access remotely, which is not restricted by IP
pwm呼吸灯
PCL 最小中值平方法拟合平面
618深度複盤:海爾智家的制勝方法論
618 deep resumption: Haier Zhijia's winning methodology
Yyds dry goods inventory has not revealed the artifact? Valentine's Day is coming. Please send her a special gift~
Kubernetes three open interfaces first sight
The login box of unity hub becomes too narrow to log in
LeetCode 4. 寻找两个正序数组的中位数(hard)
Thinking about absolute truth and relative truth
R及RStudio下载安装教程(超详细)
Multi task prompt learning: how to train a large language model?
大厂面试总结大全
亚马逊云科技 Community Builder 申请窗口开启
Xiaopeng P7 had an accident on rainy days, and the airbag did not pop up. Official response: the impact strength did not meet the ejection requirements
C语言中sprintf()函数的用法