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

    参考ObjectPool对象池设计原理还原一个简易的Provider模式. using System; using System.Dynamic; using System.Reflection.Me ...

  2. keras实现mnist手写数字数据集的训练

    网络:两层卷积,两层全连接,一层softmax 代码: import numpy as np from keras.utils import to_categorical from keras imp ...

  3. 优先队列与TopK

    一.简介 前文介绍了<最大堆>的实现,本章节在最大堆的基础上实现一个简单的优先队列.优先队列的实现本身没什么难度,所以本文我们从优先队列的场景出发介绍topK问题. 后面会持续更新数据结构 ...

  4. C#_.NetCore_WebAPI项目_EXCEL数据导出(ExcelHelper_第二版_优化逻辑)

    项目需要引用NPOI的Nuget包:DotNetCore.NPOI-v1.2.2 本篇文章是对WebAPI项目使用NPOI操作Excel时的帮助类:ExcelHelper的改进优化做下记录: 备注:下 ...

  5. 爬虫(九):python操作MySQL、MongoDB

    1. python操作MySQL 1.1 MySQL基础 在java基础部分就写过了. https://www.cnblogs.com/liuhui0308/p/11891844.html 1.2 p ...

  6. Python学习之编码

    Python2默认解释器的编码:ascii: Python3默认解释器的编码:UTF-8 ascii码:只会识别英文字母.数字和标点.8位表示一个英文字符,1个字节 万国码Uicode:目前的所有语言 ...

  7. JS---part5 课程介绍 & part4 复习

    part5 课程介绍 另一个定时器 第一个定时器的小案例----练习 封装动画函数----------匀速的动画函数,过渡到=======>缓动的动画函数 简单的轮播图 左右焦点的轮播图 无缝连 ...

  8. 软件开发工具(第8章:Eclipse工作台)

    一.初识Eclipse工作台 Eclipse 工作台(Workbench)是一个高级用户界面框架,它为用 户提供了一个整体结构和可扩展的用户界面. 什么是工作空间(记忆) 工作空间(Workspace ...

  9. day04逻辑运算符短路、多分支结构(if和switch)、循环结构、while循环

    复习 1.运算符和表达式 1)表达式 2)算数运算符 + - * / % 3)关系运算符 >  <  >=  <=  ==  != 4)逻辑运算符 &&   | ...

  10. css: hide or dispaly div

    <!DOCTYPE html> <html> <head><meta http-equiv="Content-Type" content= ...