类printf函数中[.*]的巧用场景

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值