例子在《C Primer Plus》书上有:
#include <stdio.h>
#define BLIRB "Authentic imitation!"
int main()
{
printf("[%s]\n", BLIRB);
printf("[%2s]\n", BLIRB);
printf("[%24s]\n", BLIRB);
printf("[%24.5s]\n", BLIRB);
printf("[%-24.5s]\n", BLIRB);
return 0;
}
输出结果:
[Authentic imitation!]
[Authentic imitation!]
[ Authentic imitation!]
[ Authe]
[Authe ]
%s 输出字符;
%2s 字段长度为2,当字段长度小于字符本身字段长度时,可以扩大容纳所有字符;
%24s 字段长度为24,字符长度不都则用空格填充,右对齐;
%24.5s 精度限制待打印字符个数, .5告诉printf() 只打印5个字符;
%-24.5s -标记使文本左对齐。
本文通过一个C语言示例介绍了printf函数中格式化字符串的使用方法,包括字段宽度、对齐方式及字符限制等特性。
3万+

被折叠的 条评论
为什么被折叠?



