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

    静态文件配置******* 为什么用户在浏览器中输入的网址能够访问到对应的资源, 前提是后端提前开设该资源的访问,在urls.py文件中进行配置该路由, 如果我的后端没有开设相关的资源,用户是无法访问 ...

  2. three.js 制作太阳系统

    最近学了three.js,想拿来练练手,喜欢宇宙,于是亲手撸代码来完成这个,为了更真实,于是查了一些相关资料.1. 距离太阳由近及远分别是[水星,金星,地球,火星,木星,土星,天王星,海王星]2. 他 ...

  3. VS2019 开发Django(十)------JavaScript与Django的数据交互

    导航:VS2019开发Django系列 这一篇介绍如何使用BootStrap Table这个组件来绑定渲染数据, 1)先来看一下BootStrap Table是怎么绑定数据的. 通过数据属性 给定da ...

  4. soapUI 之 测试文件上传 [6]

    在接口测试中会遇到需要上传文件的操作,比如头像修改等.那么soapui是怎么实现这部分测试的呢.以下以文件上传接口为例. 一.获取文件上传接口 可以通过开发直接提供的接口文档,或者自己抓包获取接口信息 ...

  5. 一目了然卷积神经网络 - An Intuitive Explanation of Convolutional Neural Networks

    An Intuitive Explanation of Convolutional Neural Networks 原文地址:https://ujjwalkarn.me/2016/08/11/intu ...

  6. WPF 3D球及进阶玩法

    在WPF中3D球的构建算法请参考: https://www.cnblogs.com/lonelyxmas/p/9844951.html 好玩以及值得借鉴的Demo:   (CSDN下载需要积分,避免你 ...

  7. Flipcart 爬取流程

    第一步:爬取分类url from requests_html import HTMLSession session =HTMLSession() #https://www.flipkart.com/l ...

  8. day 27-1 反射、内置方法

    反射 反射:通过字符串来映射到对象的属性 class People(): def __init__(self, name, age): self.name = name self.age = age ...

  9. php 将科学计算法得出的结果转换成原始数据 NumToStr

    由于php最大只支持显示 15位因的数据运算,大于15位的2数加减乘除的数据的结果,会直接用科学计数法显示, 但在现实生活中,科学计数法不利于普通人识别,所以,本函数将:科学计数法的出的结果转换成原始 ...

  10. 一文彻底搞清楚 Material Design

    一文彻底搞清楚 Material Design 首先声明以下介绍的关于 Material Design 的介绍,都是基于在 Android 环境下,其实 Material Design 是一种为了让 ...