当前位置:网站首页>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
边栏推荐
- DigiCert SSL证书支持中文域名申请吗?
- Rock PI Development Notes (II): start with rock PI 4B plus (based on Ruixing micro rk3399) board and make system operation
- pwm呼吸灯
- 串口控制舵机转动
- 学习周刊-总第60期-2022年第25周
- Multi task prompt learning: how to train a large language model?
- AcWing 300. Task arrangement
- [fluent] dart data type boolean type (boolean type definition | logical operation)
- What is normal distribution? What is the 28 law?
- john爆破出现Using default input encoding: UTF-8 Loaded 1 password hash (bcrypt [Blowfish 32/64 X3])
猜你喜欢

How to choose the right kubernetes storage plug-in? (09)

Just a coincidence? The mysterious technology of apple ios16 is even consistent with the products of Chinese enterprises five years ago!

你想要的宏基因组-微生物组知识全在这(2022.7)

Seal Library - installation and introduction

The login box of unity hub becomes too narrow to log in

Executive engine module of high performance data warehouse practice based on Impala

LeetCode 1. Sum of two numbers

Classifier visual interpretation stylex: Google, MIT, etc. have found the key attributes that affect image classification

隐私计算技术创新及产业实践研讨会:学习
![John blasting appears using default input encoding: UTF-8 loaded 1 password hash (bcrypt [blowfish 32/64 x3])](/img/4c/ddf7f8085257d0eb8766dbec251345.png)
John blasting appears using default input encoding: UTF-8 loaded 1 password hash (bcrypt [blowfish 32/64 x3])
随机推荐
[cloud native] briefly talk about the understanding of flume, a massive data collection component
Cloud native cicd framework: Tekton
入行数字IC验证后会做些什么?
John blasting appears using default input encoding: UTF-8 loaded 1 password hash (bcrypt [blowfish 32/64 x3])
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
OpenPose的使用
PCL 点云镜像变换
Machine learning perceptron model
PCL point cloud image transformation
L'explosion de John utilise l'encodage d'entrée par défaut: UTF - 8 Loaded 1 password Hash (bcrypt [blowfish 32 / 64 X3])
LeetCode 4. Find the median (hard) of two positive arrays
System Verilog实现优先级仲裁器
[fluent] dart data type boolean type (boolean type definition | logical operation)
路由模式:hash和history模式
Ranger (I) preliminary perception
P6774 [noi2020] tears in the era (block)
PCL 最小中值平方法拟合平面
Global and Chinese markets for airport baggage claim conveyors 2022-2028: technology, participants, trends, market size and share Research Report
js删除字符串中的子串
What is the difference between JSP and servlet?