C语言格式化输入、输出
简介
Streams provide communication channels between files and programs.
流提供文件和程序之间的通信通道。
All input and output is performed with streams, which are sequences of bytes.
所有输入和输出都是通过流(字节序列)执行的。
When program execution begins, three streams are connected to the program automatically. Normally, the standard input stream is connected to the keyboard and the standard output stream is connected to the screen. Operation systems often often allow these streams be redirected to other devices. A third stream, the standard error stream, is connected to the screen. Error messages are output to the standard error stream.
当程序开始执行时,三个流会自动连接到程序。通常,标准输入流连接到键盘,标准输出流连接到屏幕。操作系统通常允许将这些流重定向到其他设备。第三个流,标准错误流,连接到屏幕。错误消息输出到标准错误流。
The standard input, standard output and standard error are manipulated using file pointers stdin, stdout and stderr.
standard stream | file pointer | devices |
---|---|---|
标准输入 | stdin | 键盘 |
标准输出 | stdout | 屏幕 |
标准错误 | stderr | 屏幕 |
使用printf函数格式化输出
Precise output formatting is accomplished with printf. Ever printf call contains a format control string that describes the output format. The format control string consists of conversion specifiers, flags, field widths, precisions and literal characters. Together with the percent sign
%
, these form conversion specifications.
精确的输出格式化是通过 printf 完成的。每个 printf 调用都包含一个描述输出格式的格式控制字符串。格式控制字符串由转换说明符、标志、字段宽度、精度和文字字符组成。 这些与百分号 %
一起形成转换规范。
函数 printf 的格式为:
printf ( format-control-string , other-arguments ) ; {\text{printf}{\left({\textit{format-control-string},{\textit{other-arguments}}} \right)}}; printf(format-control-string,other-arguments);
format-control-string describes the output format, and other-arguments(which are optional) correspond to each conversion specification in format-control-string. Each conversion specification begins with a precent sign and ends with a conversion specifier. There can be many conversion specifications in the format control string.
format-control-string 描述输出格式,other-arguments(可选)对应于 format-control-string 中的每个转换规范。每个转换规范都以前置符号开始,并以转换说明符结束。格式控制字符串中可以有多种转换规范。
整数转换说明符
Integer Conversion Specifiers | Explanation |
---|---|
d or I | 显示有符号的十进制整数。 |
o | 显示无符号八进制整数。 |
u | 显示无符号十进制整数。 |
x or X | 显示无符号的十六进制整数。 “X”显示为大写,“x”显示为小写。 |
h or l | Place before any integer conversion specifier to indicate that a short or long integer is displayed respectively. Letters h and l are more precisely call length modifiers.放置在任何整数转换说明符之前,以指示分别显示 short 或 long 整数。 字母 h 和 l 更准确地称为长度修饰符。 |
浮点数转换说明符
Float |
---|