当前位置:网站首页>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
边栏推荐
- LeetCode 4. Find the median (hard) of two positive arrays
- Masa framework - DDD design (1)
- L'explosion de John utilise l'encodage d'entrée par défaut: UTF - 8 Loaded 1 password Hash (bcrypt [blowfish 32 / 64 X3])
- 国内比较好的OJ平台[通俗易懂]
- Seal Library - installation and introduction
- unity Hub 登录框变得很窄 无法登录
- unity Hub 登錄框變得很窄 無法登錄
- The login box of unity hub becomes too narrow to log in
- 学生选课系统(山东农业大学课程设计)
- False summer vacation
猜你喜欢
The login box of unity hub becomes too narrow to log in
Résumé de l'entrevue de Dachang Daquan
In MySQL and Oracle, the boundary and range of between and precautions when querying the date
Digital IC hand tearing code -- voting device
PCL 点云镜像变换
[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
电脑自带软件使图片底色变为透明(抠图白底)
Typescript array out of order output
关于举办科技期刊青年编辑沙龙——新时代青年编辑应具备的能力及提升策略的通知...
How openharmony starts FA of remote devices
随机推荐
Learning Weekly - total issue 60 - 25th week of 2022
What is normal distribution? What is the 28 law?
Written by unity Jason
[fluent] dart data type list set type (define set | initialize | generic usage | add elements after initialization | set generation function | set traversal)
PCL 点云镜像变换
小鹏P7雨天出事故安全气囊没有弹出 官方回应:撞击力度未达到弹出要求
Serial port controls steering gear rotation
C语言自定义函数的方法
Deep learning image data automatic annotation [easy to understand]
TCP congestion control details | 2 background
In MySQL and Oracle, the boundary and range of between and precautions when querying the date
Day 18 of leetcode dynamic planning introduction
Lampe respiratoire PWM
Go zero micro service practical series (VIII. How to handle tens of thousands of order requests per second)
vscode设置删除行快捷键[通俗易懂]
PCL point cloud image transformation
A week of short video platform 30W exposure, small magic push helps physical businesses turn losses into profits
OpenPose的使用
pwm呼吸灯
C语言中sprintf()函数的用法