---
title: "printf格式化转换说明"
author: "clouisandy"
date: "2011-09-15T21:08:00Z"
tags: []
categories: ["编程语言"]
slug: "printf"
draft: false
lastmod: "2011-09-15T21:09:31Z"
id: 1172905
url: "https://clouisandy.iteye.com/blog/1172905"
---

```&quot;c&quot;
int printf(char *format,arg1,arg2,...)
```



这样printf常用，第一个参数是要输出的内容，后面是变量列表，这样函数会将format变量中的“%xxxx”替换成后面的变量arg1~argn 

下面介绍一下这些“%xxxx”，如“%-15.10s”分两个部分，前面的&quot;-15.10&quot;是对格式的限定，后面的“s”是对类型的限定。先说格式的限定：


符号(-) ，左对齐

数字(123)，最小字段宽度，不够的填充空格，往哪边填充要看对齐方式了

小数点(.)，指定精度，如果是字符串那就是打印的最大字符数，如果是浮点数即小数点后的最少位数，如果是整数即最少输出的数字数目



再说类型的限定：


h或l，h是short类型打印，l是long类型打印 

d或i，int类型，10进制

o，int类型，无符号8进制

x或X，int类型，无符号16进制

u，int类型，无符号10进制

c，单个字符

s，字符串

f，double类型

e或E，double类型，科学技术法表示

g或G，double类型，选择性地打印科学计数法，如果指数的精度小于-4或者大于等于精度，则用科学计数法，否则正常%f输出

p，void *类型，指针

%，打印%


如果觉得抽象，看下面例子就明白了：


```&quot;例子&quot;
main()
{
	printf(&quot;%.*s\n&quot;,5,&quot;hello,world&quot;);//hello “×”可以被后面的整型数字替换

	printf(&quot;%s\n&quot;,&quot;hello,world&quot;);//hello,world
	printf(&quot;%10s\n&quot;,&quot;hello,world&quot;);//hello,world
	printf(&quot;%.10s\n&quot;,&quot;hello,world&quot;);//hello,worl
	printf(&quot;%.15s\n&quot;,&quot;hello,world&quot;);//hello,world
	printf(&quot;%15.10s\n&quot;,&quot;hello,world&quot;);//     hello,worl 最小宽度为15，最大字符数为10，所以‘d’没有打印出来，并且右对齐
	printf(&quot;%-15.10s\n&quot;,&quot;hello,world&quot;);//hello,worl 同上，左对齐

	printf(&quot;%o\n&quot;,10);//12 八进制的10
	printf(&quot;%x\n&quot;,17);//11 十六进制的17
	printf(&quot;%f\n&quot;,1234567.1234567);//1234567.123457 注意后面的6变为了7，默认的f精度为6，所以四舍五入了
	printf(&quot;%e\n&quot;,1234567.1234567);//1.234567e+006
	printf(&quot;%E\n&quot;,1234567.1234567);//1.234567E+006 e变为大写的了
	printf(&quot;%g\n&quot;,123456.123456);//123456 精度为6，指数为5，正常输出
	printf(&quot;%g\n&quot;,1234567.1234567);//1.23457e+006 精度为6，指数为6，用科学计数法

	char p[100];
	printf(&quot;%p\n&quot;,p);//0022FF00
	printf(&quot;%%\n&quot;);//%

	char s[100];
	sprintf(s,&quot;%g\n&quot;,1234567.1234567);//将内容输入到s中
	printf(&quot;%s\n&quot;,s);//1.23457e+006
}
```



上面顺便说了一下“sprintf”的用法