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()函数里的作用是用来设置精度。