Cprogramming 简明教程

Format Specifiers in C

C 中的格式说明符是在格式化控制台 IO 函数(比如 printf() 和 scanf())和格式化文件 IO 函数(比如 fprintf() 和 fscanf())中使用的特定特殊符号。

Format specifiers in C are certain special symbols used in the formatted console IO functions such as printf() and scanf(), as well as formatted file IO functions such as fprintf() and fscanf().

格式说明符由一个或多个字母数字字符组成的预定义序列加上 % 符号构成。例如,%d、%s、%f、%lf 等等是 C 中使用的一些格式说明符。

Format specifiers are formed of a predefined sequence of one or more alphanumeric characters followed by the % symbol. For example, %d, %s, %f, %lf, etc. are some of the format specifiers used in C.

Why Do We Use Format Specifiers in C?

CPU 以流的方式执行输入和输出设备的 IO 操作。通过标准输入流从标准输入设备(例如,键盘)读取的数据称为 stdin 。类似地,通过标准输出设备发送到标准输出的(即计算机显示屏)数据称为 stdout

The CPU performs IO operations with input and output devices in a streaming manner. The data read from a standard input device (for example, a keyboard) through the standard input stream is called stdin. Similarly the data sent to the standard output, which is the computer display screen, through the standard output device is called stdout.

计算机以文本形式从流接收数据,但你可能想把它解析成不同数据类型的变量,比如 int、float 或字符串。类似地,存储在 int、float 或 char 变量中的数据必须以文本格式发送到输出流。格式说明符符号正是出于这个目的而使用的。

The computer receives data from the stream in a text form, however you may want to parse it in variables of different data types such as int, float or a string. Similarly, the data stored in int, float or char variables has to be sent to the output stream in a text format. Format specifier symbols are used exactly for this purpose.

Format Specifiers in printf() Function

printf() 函数是使用最广泛的标准输出函数,在 stdio.h 头文件中定义。printf() 函数的原型如下:

The printf() function is the most commonly used standard output function, defined in the stdio.h header file. The prototype of printf() function is as follows −

int printf(format_string, expr1, expr2, . . );

这个函数的第一个参数是一个穿插着一个或多个格式说明符的字符串。第一个参数后面可以有一个或多个表达式作为参数。编译器用每个格式说明符替换它相继表达式的值。然后结果格式化字符串被传递到输出流。

The first argument of this function is a string that is interspersed with one or more format specifiers. There may be one or more expressions as argument after the first. The compiler substitutes each format specifier with the value of its successive expression. The resultant formatted string is then passed to the output stream.

Example

在下面的代码中,我们有一个 int 变量 age 和一个 float 变量 percent 。printf() 函数打印这两个值,如下所示。

In the following code, we have an int variable age and a float variable percent. The printf() function prints the values of both as below −

#include <stdio.h>

int main(){

   int age = 18;

   float percent = 67.75;

   printf("Age: %d \nPercent: %f", age, percent);

   return 0;
}

当你运行此代码时,它将会生成以下输出:

When you run the code, it will produce the following output −

Age: 18
Percent: 67.750000

第一个变量的值替换第一个格式说明符 %d 。类似地, %f 被变量的百分比值替换。

The value of the first variable replaces the first format specifier %d. Similarly, %f is substituted by the value of the percent variable.

Format Specifiers in scanf() Function

格式说明符还用于将输入流解析成所需类型的变量。下面的例子突出了它是如何完成的。

Format specifiers are also used to parse the input stream into the variables of required type. The following example highlights how it’s done.

Example

在这个例子中,程序要求用户输入年龄和百分比值。它们分别存储在 int 和 float 变量中。

In this example, the program asks the user to input age and percent values. They are stored in the int and float variables, respectively.

#include <stdio.h>

int main(){

   int age;

   float percent;

   printf("Enter Age and Percent: \n");

   scanf("%d %f", &age, &percent);

   printf("Age: %d Percent: %f", age, percent);

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

Enter Age and Percent:
Age: 4096 Percent: 0.000000

Types of Format Specifiers

ANSI C 定义了许多格式说明符。下表列出了不同的说明符及其用途:

ANSI C defines a number of format specifiers. The following table lists the different specifiers and their purpose −

Format Specifier

Type

%c

Character

%d

Signed integer

%e or %E

Scientific notation of floats

%f

Float values

%g or %G

Similar as %e or %E

%hi

Signed integer (short)

%hu

Unsigned Integer (short)

%i

Unsigned integer

%l or %ld or %li

Long

%lf

Double

%Lf

Long double

%lu

Unsigned int or unsigned long

%lli or %lld

Long long

%llu

Unsigned long long

%o

Octal representation

%p

Pointer

%s

String

%u

Unsigned int

%x or %X

Hexadecimal representation

  1. A minus symbol () tells left alignment.

  2. A number after % specifies the minimum field width. If a string is less than the width, it will be filled with spaces.

  3. A period (.) is used to separate field width and precision.

Integer Format Specifiers

C 使用 %d 表示带符号整数, %i 表示无符号整数, %ld%li 表示长整数, %o%O 表示八进制表示, %x%X 表示整数的十六进制表示。

C uses %d for signed integer, %i for unsigned integer, %ld or %li for long integer, %o or %O for octal representation, and %x or %X for hexadecimal representation of an integer.

Example

以下示例突出显示了在 C 中如何使用整数格式说明符 −

The following example highlights how integer format specifiers are used in C −

#include <stdio.h>

int main(){

   int num = 20;

   printf("Signed integer: %d\n", num);
   printf("Unsigned integer: %i\n", num);
   printf("Long integer: %ld\n", num);
   printf("Octal integer: %o\n", num);
   printf("Hexadecimal integer: %x\n", num);

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

Signed integer: 20
Unsigned integer: 20
Long integer: 20
Octal integer: 24
Hexadecimal integer: 14

Floating-point Formats

C 使用 %f 格式说明符表示单精度浮点数, %lf 表示双精度, %Lf 表示长双精度数。C 使用 %e%E 说明符符号来表示科学记数法的浮点数。

C uses the %f format specifier for single precision float number, %lf for double precision, %Lf for long double number. To represent a floating point number in scientific notation, C uses the %e or %E specifier symbol.

您可以以小数点后位数的形式指定宽度和精度。例如,要将数字的宽度指定为 4 位,小数点后 2 位,请使用 %4.2f 表单。

You can specify the width and the precision in the form of number of places after the decimal point. For example, to state the width of number to 4 digits with 2 digits after the decimal point, use the form %4.2f.

Example

请看以下示例:

Take a look at the following example −

#include <stdio.h>

int main(){

   float num = 5.347;

   printf("float: %f\n", num);
   printf("double: %lf\n", num);
   printf("Scientific notation: %e\n", num);
   printf("width and precision: %4.2f\n", num);

   return 0;
}

运行此代码,您将获得以下输出−

On running this code, you will get the following output −

float: 5.347000
double: 5.347000
Scientific notation: 5.347000e+000
width and precision: 5.35

String Formats

C 中的 char 数据类型实际上是 int 数据类型的子集。因此,带有 %c 格式说明符的 char 变量对应于单引号中的字符。另一方面,如果您使用 %d 说明符,则 char 变量将格式化为其 ASCII 值。

The char data type in C is actually a subset of int data type. Hence, a char variable with %c format specifier corresponds to the character in single quotes. On the other hand, if you use the %d specifier, then the char variable will be formatted to its ASCII value.

在 C 中,字符串是 char 数据的数组。C 使用 %s 说明符来显示 char 数组。

In C, a string is an array of char data. To display an array of chars, C uses the %s specifier.

Example

请看以下示例:

Take a look at the following example −

#include <stdio.h>

int main(){

   char ch = 'D';
   char word[]="Hello World";

   printf("As character: %c\n", ch);
   printf("As its ASCII value: %d\n", ch);
   printf("String format: %s", word);

   return 0;

}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

As character: D
As its ASCII value: 68
String format: Hello World

Format Specifiers in File IO Functions

stdio.h 库为磁盘文件定义了函数 fscanf()fprintf() ,用于格式化 IO,而不是标准输入/输出流。

The stdio.h library defines the functions fscanf() and fprintf() for formatted IO with disk files, instead of standard input/output streams.

Example 1

以下代码以写入模式打开一个文件,并将其中的三个变量的值保存到该文件中。

The following code opens a file in write mode and saves the values of three variables in it.

#include <stdio.h>

int main(){

   int x,y,z;

   FILE *fp = fopen("test.txt","w");

   x = 10; y = 20; z = 30;

   fprintf(fp, "%d, %d, %d", x,y,z);

   fclose(fp);

   return 0;
}
The fprintf() function uses the file represented by the file pointer fp to write the data.

下一个示例显示了如何以读取模式打开同一文件来读取格式化数据。

The next example shows how you can open the same file in read mode to read the formatted data.

Example 2

以下程序通过以读取模式打开文件来从该文件中读取数据。

The following program reads back the data from the file by opening it in read mode.

#include <stdio.h>

int main(){

   int x,y,z;

   FILE *fp = fopen("test.txt","r");

   fscanf(fp, "%d, %d, %d", &x,&y,&z);

   printf("%d, %d, %d", x,y,z);

   fclose(fp);

   return 0;
}

fscanf() 函数从 fp 读取格式化的输入,它是打开文件的指针。在此,您将获得以下输出 −

The fscanf() function reads the formatted input from fp which is the pointer to the file opened. Here, you will get the following output −

10, 20, 30