作为强类型静态语言,类型不仅规定了可以对数据进行的操作,还决定了应该怎样在 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. 手动SQL注入原理分析与实践

    代码仓库 本文所用代码的代码库地址: 点击这里前往Github仓库 了解SQL注入 定义 SQL注入攻击(SQL Injection),简称注入攻击,是Web开发中最常见的一种安全漏洞.可以用它来从数 ...

  2. 《Java知识应用》Java压缩文件和解压缩

    今天通过Java实现一下:文件的压缩和解压缩. 1. 压缩 准备文件: 准备代码:(压缩) import java.io.BufferedInputStream; import java.io.Buf ...

  3. 通过 Drone Rest API 获取构建记录日志

    Drone是一款CICD工具,提供rest API,简单介绍下如何使用API 获取构建日志. 获取token 登录进入drone,点头像,在菜单里选择token 复制token即可 API 介绍 Dr ...

  4. 升级sharepoint2013遇到的坑

    现在要将sharepoint2010,ProjectServer2010升级到2016的版本,需要先升级到2013的版本. 按照官方文档,瞎搞将sharepoint2010升级到2013的版本,中间出 ...

  5. iOS:bugly符号表上传

    https://blog.csdn.net/weixin_38633659/article/details/81667721 这个篇文章已经讲得足够清楚 而且官方的文档也写得很好(注意官方网站上的文档 ...

  6. asp.net core react 项目实战(一)

    asp.net-core-react asp.net core react 简介 开发依赖环境 .NET Core SDK (reflecting any global.json): Version: ...

  7. Linux - CentOS 7 通过Yum源安装 MySql 5.7

    添加MySQL Yum存储库 从官网下载最新的mysql源 官网地址:https://dev.mysql.com/downloads/repo/yum/ 选择并下载适用于平台的发行包. 然后,在Lin ...

  8. python通过http下载文件的方法

    1.通过requests.get方法 r = requests.get("http://200.20.3.20:8080/job/Compile/job/aaa/496/artifact/b ...

  9. 转pytorch中训练深度神经网络模型的关键知识点

    版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/weixin_42279044/articl ...

  10. C#_.NetCore_Web项目_EXCEL数据导出(ExcelHelper_第一版)

    项目需要引用NPOI的Nuget包:DotNetCore.NPOI-v1.2.2 A-前端触发下载Excel的方法有三种: 1-JS-Url跳转请求-后台需要返回文件流数据: window.Locat ...