作为强类型静态语言,类型不仅规定了可以对数据进行的操作,还决定了应该怎样在 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

相关资源

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

  1. Linux中printf格式化输出

    printf使用文本或者由空格分隔的参数,我们可以在printf中使用格式化字符串.printf不会写像echo那样自动添加换行符,必须手动添加 =========================== ...

  2. 单片机中printf函数的重映射

    单片机中printf函数的重映射 一.源自于:大侠有话说 1.如果你在学习单片机之前学过C语言,那么一定知道printf这个函数.它最最好用的功能 除了打印你想要的字符到屏幕上外,还能把数字进行格式化 ...

  3. C语言 printf格式化输出,参数详解

      有关输出对齐 int main(int argc, char* argv[]){ char insertTime[20] = {"1234567890"}; double in ...

  4. (Go)06. Printf格式化输出、Scanf格式化输入详解

    Print.Println .Printf .Sprintf .Fprintf都是fmt 包中的公共方法,在需要打印信息时需要用到这些函数,那么这些函数有什么区别呢? Print: 输出到控制台(不接 ...

  5. linux 中printf的使用

    linux 中printf的使用printf "helloworld\n"printf 中换行必须加上\n printf '%d %s\n' 1 "abc" c ...

  6. Printf 格式化简要总结

    格式代码 A ABC ABCDEFGH %S A ABC ABCDEFGH %5S ####A ##ABC ABCDEFGH %.5S A ABC ABCDE %5.5S ####A ##ABC AB ...

  7. WPF中StringFormat 格式化 的用法

    原文 WPF中StringFormat 格式化 的用法 网格用法 <my:DataGridTextColumn x:Name="PerformedDate" Header=& ...

  8. ruby中printf "%x"%-4为何会打印开头..

    先看一下ruby中printf "%x" % -4的返回结果: irb(main):134:0> printf "%x\n" % -4 ..fc 前面的. ...

  9. Lodop的TABLE中format格式化的使用

    LODOP中的ADD_PRINT_TABLE支持很多函数和计算方法,可以用tdata对table表格里额数据进行计算,用format对结果进行格式化.这个format只能和tdata搭配使用,不能单独 ...

随机推荐

  1. mysql5.7搭建主从库

    #MYSQL单节点的mysql远远不能满于生成,以防止生产服务器宕机,磁盘空间溢满等种种原因,需要有一个备用数据库, 这时候主从库是不错的选择,在是数据库集群中也起到了很大的作用 #MySQL 主从复 ...

  2. java基础-初识类

    一 前言 在 <[java基础]-谈谈对面向对象理解 >一文中已经知道什么是对象,如何创建对象:这篇文章主讲对象的类型,简称类: 二 类介绍 2.1 类 每个对象都有一个类型,通常在所有的 ...

  3. QT--TCP网络编程(客户端/服务器)

    QT -----TCP网络编程   1.主要流程 1.客户端 创建QTcpSocket对象 连接到服务器 --connectToHost() 发送数据 ---write() 读取数据 ---readA ...

  4. 使用PHP生成并导出CSV文件

    CSV文件是以纯文本形式存储的,一般以逗号为分隔符.这里主要简单介绍下如何导出CSV文件. 一.浏览器导出CSV文件格式 /** * 导出CSV文件 */ function exportCsv() { ...

  5. <科普>CPU进行四则运算(加减乘除)的主流方法

    以下除特殊说明外均为32位数的运算 1.加法运算 A   +   B    =   C 无符号整数加法和有符号整数加法均采用以下方案进行操作 用到的寄存器与初始化内容: 32位加数寄存器------- ...

  6. 【SVN搭建】搭建SVN服务

    1.安装 # yum -y install subversion 2.配置 创建仓库 我们这里在/opt下建立一个名为svn的仓库(repository),所有代码都可以放在这个下面,创建成功后在sv ...

  7. 如何Windows下配置Prometheus的监控数据文件为3天

    如上图,prometheus的data文件夹时间久了会变得很大,听说是保留15天的数据.但是实际上,我只需要保留3天的数据就够了,之前试过用批处理文件清理,但是强行删除会导致peometheus崩溃, ...

  8. 通过Ajax的访问zuul的跨域问题解决方案

    刚开始在使用jqueryajax跨域请求zuul网关时,在后台发现一直拿不到前台请求的json数据,而前台也一直拿不到后台的响应数据.打开浏览器调试程序发现,本身ajax的POST请求统一都变成了op ...

  9. 一分钟理解Java公平锁与非公平锁

    本人免费整理了Java高级资料,涵盖了Java.Redis.MongoDB.MySQL.Zookeeper.Spring Cloud.Dubbo高并发分布式等教程,一共30G,需要自己领取.传送门:h ...

  10. UI_DEV_Environment 之 StoryBook

    写在前面 由于本文主要集中关注与工具使用,所以不可能完全介绍工具的所有功能,所以要想了解更多,可以自己去各自官方网站上查看. github examples 什么是UI开发环境 UI开发环境专注于用户 ...