C/C++ 中 `printf` 格式化


作为强类型静态语言,类型不仅规定了可以对数据进行的操作,还决定了应该怎样在 printf 中输出。

printf 的签名是:

int printf ( const char * format, ... );

其中 format 为可以参参数格式化的输出内容。具体格式化形式为:

%[flags][width][.precision][length]specifier

% 开头,紧跟一些用于格式化的修饰符,其中 [flags][width][.precision][length] 这些为可选部分,称为 sub-specifier,重点是 specifier,它与数据类型便有对应关系了。

一些简单示例:

// 打印整形
int age=20;
printf("My age is %d",age);

// 打印字符串
char[] name="poftut";
printf("Name: %s",name);

// 同时打印多个变量
char[] name="poftut";
int age=2;
char[] city = "ankara";
printf("Name:%s , Age:%d , City:%s",name, age, city);

specifier

可选的 specifier 以及对应的数据类型见如下来自 C++ Reference 的表格:

specifier 输出描述 输出示例
d or i Signed decimal integer 392
u Unsigned decimal integer 7235
o Unsigned octal 610
x Unsigned hexadecimal integer 7fa
X Unsigned hexadecimal integer (uppercase) 7FA
f Decimal floating point, lowercase 392.65
F Decimal floating point, uppercase 392.65
e Scientific notation (mantissa/exponent), lowercase 3.9265e+2
E Scientific notation (mantissa/exponent), uppercase 3.9265E+2
g Use the shortest representation: %e or %f 392.65
G Use the shortest representation: %E or %F 392.65
a Hexadecimal floating point, lowercase -0xc.90fep-2
A Hexadecimal floating point, uppercase -0XC.90FEP-2
c Character a
s String of characters sample
p Pointer address b8000000
n Nothing printed.
The corresponding argument must be a pointer to a signed int.
The number of characters written so far is stored in the pointed location.
% A % followed by another % character will write a single % to the stream. %

flag

flags description
- Left-justify within the given field width; Right justification is the default (see width sub-specifier).
+ Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
(space) If no sign is going to be written, a blank space is inserted before the value.
# Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero.
Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
0 Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).

width

width description
(number) Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
* The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

precision

.precision description
.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 a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
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.
If the period is specified without an explicit value for precision, 0 is assumed.
.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

length

length 长度 sub-specifier用来补充修饰数据类型的长度。部分数据类型会有长度的变种,便可用此 sub-specifier 来标识。它与 spcifier 的组合所表示的数据类型见下表:

length int unsigned int double int char* void* int*
hh signed char unsigned char signed char*
h short int unsigned short int short int*
l long int unsigned long int wint_t wchar_t* long int*
ll long long int unsigned long long int long long int*
j intmax_t uintmax_t intmax_t*
z size_t size_t size_t*
t ptrdiff_t ptrdiff_t ptrdiff_t*
L long double

另外一些示例

int encode(const short* buffer_l, int mp3buf_size) {
  printf("addr is %p ,size is %i\n", buffer_l,mp3buf_size);
}

注意这里 %p,对照上面 specifier 表格可知它代表指针,这里用其他类型都不能匹配。

来自的示例:

/* printf example */
#include <stdio.h>

int main()
{
   printf ("Characters: %c %c \n", ‘a‘, 65);
   printf ("Decimals: %d %ld\n", 1977, 650000L);
   printf ("Preceding with blanks: %10d \n", 1977);
   printf ("Preceding with zeros: %010d \n", 1977);
   printf ("Some different radices: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
   printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
   printf ("Width trick: %*d \n", 5, 10);
   printf ("%s \n", "A string");
   return 0;
}

输出:

Characters: a A
Decimals: 1977 650000
Preceding with blanks:       1977
Preceding with zeros: 0000001977
Some different radices: 100 64 144 0x64 0144
floats: 3.14 +3e+000 3.141600E+000
Width trick:    10
A string

相关资源

原文地址:https://www.cnblogs.com/Wayou/p/c_format_specifier.html

时间: 2024-10-19 03:24:17

C/C++ 中 `printf` 格式化的相关文章

printf格式化打印

格式代码 A ABC ABCDEFGH %S A ABC ABCDEFGH %5S ####A ##ABC ABCDEFGH %.5S A ABC ABCDE %5.5S ####A ##ABC ABCDE %-5S A#### ABC## ABCDEFGH Printf 格式化字符串 格式代码 1 -12 12345 123456789 %d 1 -12 12345 123456789 %6d #####1 ###-12 #12345 123456789 %.4d 0001 -0012 123

实测STM32F4中printf的效率问题

实测STM32F4中printf的效率问题 一直认为printf所做的工作就是格式化字符串,然后依次调用fputc函数发送出去.于是以前都认为printf函数的瓶颈是在fputc这里,是因为发送一个字节所占的时间太长,才导致printf效率慢.也就是说,一直认为如果串口的波特率设置成115200的话,printf至少也是能达到115200的波特率的. 而这几天在学习ucOS,于是想到,如果printf的瓶颈是在等在串口发送完成的话,那么我在等待串口发送完成中断的时候是不是挂起一个信号量,然后就可

C/C++中printf和C++中cout的输出格式

C/C++中printf和C++中cout的输出格式 一. Printf 输出格式 C中格式字符串的一般形式为: %[标志][输出最小宽度][.精度][长度]类型,其中方括号[]中的项为可选项.各项的意义介绍如下: 1.类型类型字符用以表示输出数据的类型,其格式符和意义下表所示: 表示输出类型的格式字符 格式字符意义 a 浮点数.十六进制数字和p-计数法(C99) A 浮点数.十六进制数字和p-计数法(C99) c 输出单个字符 d 以十进制形式输出带符号整数(正数不输出符号) e 以指数形式输

Java中日期格式化YYYY-DD的坑

摘自:https://www.cnblogs.com/tonyY/p/12153335.html Java中日期格式化YYYY-DD的坑 2020-01-05 19:27  兔子托尼啊  阅读(115)  评论(0)  编辑  收藏 写这篇博文是记录下跨年的bug.去年隔壁组的小伙伴就是计算两个日期之间间隔的天数,因为跨年的原因计算有误. 当时测试组的小姐姐也没有模拟出来这种场景,导致上生产环境直接影响线上的数据. 今天逛技术论论坛正好遇到Java日期的操作bug. 1 yyyy 和 YYYY

(Go)15.golang printf 格式化输出

Printf 格式化输出 通用占位符: v 值的默认格式. %+v 添加字段名(如结构体) %#v 相应值的Go语法表示 %T 相应值的类型的Go语法表示 %% 字面上的百分号,并非值的占位符 布尔值: %t true 或 false 整数值: %b 二进制表示 %c 相应Unicode码点所表示的字符 %d 十进制表示 %o 八进制表示 %q 单引号围绕的字符字面值,由Go语法安全地转义 %x 十六进制表示,字母形式为小写 a-f %X 十六进制表示,字母形式为大写 A-F %U Unicod

Python中字符串格式化如何实现?

Python开发中字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存. This PEP proposes a new system for built-in string formatting operations, intended as a replacement for the existing '%' string formatting operator. 1.百分号方式 %[(na

在JS中,将text框中数据格式化,根据不同的小数位数,格式化成对应的XXX,XXX,XXX.XX(2位小数) 或者XXX,XXX,XXX(0位小数)

//在JS中,将text框中数据格式化,根据不同的小数位数,格式化成对应的XXX,XXX,XXX.XX(2位小数) 或者XXX,XXX,XXX(0位小数) function formatNum(num, n) {//参数说明:num 要格式化的数字 n 保留小数位 num = String(num.toFixed(n)); var re = /(-?\d+)(\d{3})/; while (re.test(num)) num = num.replace(re, "$1,$2") ret

linux 中printf的使用

linux 中printf的使用printf "helloworld\n"printf 中换行必须加上\n printf '%d %s\n' 1 "abc" [email protected]:~/linux$ a=2[email protected]:~/linux$ printf 'a is %s\n' $aa is 2 使用printf结合变量的使用

【转】Asp.net中时间格式化的6种方法详细总结

1. 数据控件绑定时格式化日期方法: 代码如下: <asp:BoundColumn DataField="AddTime" HeaderText="添加时间" DataFormatString="{0:yyyy-MM-dd HH:mm}></asp:BoundColumn> <asp:BoundField DataField="AddTime" HeaderText="添加时间" Dat