类printf函数中[.*]的巧用场景
2014-09-24 wcdjprintf中[.*]的用法区别.precision description[1] .number For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the
2014-09-24 wcdj
此文章的用法对应之前的一篇文章《类scanf函数中%[*]type的巧用场景》。
printf中[.*]的用法
区别
.precision description
[1] .number For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0.
For e, E and f specifiers: this is the number of digits to be printed after the decimal point.
For g and G specifiers: This is the maximum number of significant digits to be printed.
For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered.
For c type: it has no effect.
When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed.
[2] .* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
例如:
char name[]="123456789";
char *p=name+5;
printf("%.*s\n",p - name, name);// 12345
int a=12345;
printf("%.*d\n",6, a);// 012345 显示化设置精度
一个DEMO:
生成一个固定长度的随机订单号
#include <stdio.h>
#include <string.h>
#include <string>
using namespace std;
int main()
{
string str = "140924";
int order = 12345;
const int maxlen = 10;
char buf[maxlen + 1] = {0};
snprintf(buf, sizeof(buf), "%.*d", maxlen, order);
printf("buf[%s]\n", buf);
str += buf;
printf("str[%s]\n", str.c_str());
return 0;
}
/*
output:
buf[0000012345]
str[1409240000012345]
*/
总结:
类scanf()函数里的作用是跳过该参数,而类printf()函数里的作用是用来设置精度。
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)