第 164 / 187 篇

16.2. 输入/输出(printf 与 scanf)

说明

本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/Appendix1/input_output.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。

16.2. Input/Output (printf and scanf)

C 的 printf 函数把值打印到终端,scanf 函数读取用户输入的值。printf 和 scanf 函数属于 C 的标准 I/O 库,任何使用这些函数的 .c 文件都需要在开头用 #include <stdio.h> 显式引入它。本节介绍在 C 程序中使用 printf 和 scanf 的基础知识。第 2 章的「I/O」一节会更详细地讨论 C 的输入输出函数。

C’s printf function prints values to the terminal, and the scanf function reads in values entered by a user. The printf and scanf functions belong to C’s standard I/O library, which needs to be explicitly included at the top of any .c file that uses these functions by using #include <stdio.h>. In this section, we introduce the basics of using printf and scanf in C programs. The “I/O” section in Chapter 2 discusses C’s input and output functions in more detail.

16.2.1. printf

16.2.1. printf

C 的 printf 函数与 Java 中的 System.out.printf 方法非常相似,调用者都要指定一个要打印的格式字符串。格式字符串中常常包含格式说明,例如会打印出制表符(\t)或换行符(\n)的特殊字符,或者输出中各个值的占位符。占位符由 % 后跟一个类型说明字母组成(例如,%d 表示一个整数值的占位符)。对于格式字符串中的每个占位符,printf 都期望有一个额外的参数。表 1 给出了一个带格式化输出的 Java 和 C 示例程序:

C’s printf function is very similar to the System.out.printf method in Java, where the caller specifies a format string to print. The format string often contains formatting specifiers, such as special characters that will print tabs (\t) or newlines (\n), or placeholders for values in the output. Placeholders consist of % followed by a type specifier letter (for example, %d represents a placeholder for an integer value). For each placeholder in the format string, printf expects an additional argument. Table 1 contains an example program in Java and C with formatted output:

表 1. Java 与 C 中打印输出的语法比较

Table 1. Syntax Comparison of Printing in Java and C

Java 版本

Java version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* Java formatted print example */

class PrintfExample {

public static void main(String[] args){

System.out.printf("Name: %s, Info:\n",
"Vijay");
System.out.printf("\tAge: %d\t Ht: %g\n",
20, 5.9);
System.out.printf("\tYr: %d\t Dorm: %s\n",
3, "Alice Paul");
}

}

C 版本

C version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* C printf example */

#include <stdio.h> // for printf

int main(void) {

printf("Name: %s, Info:\n",
"Vijay");
printf("\tAge: %d\t Ht: %g\n",
20, 5.9);
printf("\tYr: %d\t Dorm: %s\n",
3, "Alice Paul");

return 0;
}

运行时,这个程序的两个版本会产生格式完全相同的输出:

When run, both versions of this program produce identically formatted output:

1
2
3
Name: Vijay,  Info:
Age: 20 Ht: 5.9
Year: 3 Dorm: Alice Paul

C 用与 Java 相同的格式化占位符来指定不同类型的值。前面的例子演示了下面这些格式化占位符:

C uses the same formatting placeholders as Java for specifying different types of values. The preceding example demonstrates the following formatting placeholders:

1
2
3
4
%g:  placeholder for a float (or double) value
%d: placeholder for a decimal value (int, short, char)
%s: placeholder for a string value
%c: placeholder for a char value

当程序员想打印与某个数值编码相对应的 ASCII 字符时,%c 占位符很有用。下面是一个 C 代码片段,它把一个 char 分别按数值(%d)和字符编码(%c)打印出来:

The %c placeholder is useful when a programmer wants to print the ASCII character associated with a particular numeric encoding. Here’s a C code snippet that prints a char as its numeric value (%d) and as its character encoding (%c):

1
2
3
4
5
6
7
8
9
10
// Example printing a char value as its decimal representation (%d)
// and as the ASCII character that its value encodes (%c)

char ch;

ch = 'A';
printf("ch value is %d which is the ASCII value of %c\n", ch, ch);

ch = 99;
printf("ch value is %d which is the ASCII value of %c\n", ch, ch);

运行时,程序的输出如下:

When run, the program’s output looks like this:

1
2
ch value is 65 which is the ASCII value of  A
ch value is 99 which is the ASCII value of c

16.2.2. scanf

16.2.2. scanf

C 的 scanf 函数是读取用户(通过键盘)输入的值并将其存入程序变量的一种方法。scanf 函数对用户输入数据的确切格式有些挑剔,这意味着它对格式不正确的用户输入不够健壮。在第 2 章的「I/O」一节中,我们会讨论更健壮的读取用户输入的方法。目前只要记住:如果你的程序因为格式错误的用户输入而陷入死循环,随时可以按 CTRL-C 终止它。

C’s scanf function represents one method for reading in values entered by the user (via the keyboard) and storing them in program variables. The scanf function can be a bit picky about the exact format in which the user enters data, which means that it’s not very robust to badly formed user input. In the “I/O” section in Chapter 2, we discuss more robust ways of reading input values from the user. For now, remember that if your program gets into an infinite loop due to badly formed user input, you can always press CTRL-C to terminate it.

Java 和 C 处理输入读取的方式不同:Java 创建一个新的 Scanner 对象,用它的方法读入并返回不同类型的值;而 C 用 scanf 读入由格式字符串参数指定的不同类型的值,并把它们存放到程序变量的内存位置上(例如 &num1)。表 2 展示了在 Java 和 C 中读取用户输入值的示例程序:

Reading input is handled differently in Java and C: Java creates a new Scanner object and uses its methods to read in and return values of different types, whereas C uses scanf to read in values of different types, specified by a format string argument, and store them at the memory locations of program variables (for example, &num1). Table 2 displays example programs for reading user input values in Java and C:

表 2. Java 与 C 中读取输入值的方法比较

Table 2. Comparison of Methods for Reading Input Values in Java and C

Java 版本

Java version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* Java input example */

import java.util.Scanner;

class InputExample {

public static void main(String[] args) {

int num1, num2;
Scanner in = new Scanner(System.in);

System.out.print("Enter a number: ");
num1 = in.nextInt();
System.out.print("Enter another: ");
num2 = in.nextInt();

System.out.printf( "%d + %d = %d\n",
num1, num2, (num1+num2) );
}

}

C 版本

C version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* C input (scanf) example */

#include <stdio.h>



int main(void) {

int num1, num2;


printf("Enter a number: ");
scanf("%d", &num1);
printf("Enter another: ");
scanf("%d", &num2);

printf("%d + %d = %d\n",
num1, num2, (num1+num2) );

return 0;
}

运行时,两个程序都读入两个值(这里是 30 和 67):

When run, both programs read in two values (here, 30 and 67):

1
2
3
Enter a number: 30
Enter another: 67
30 + 67 = 97

与 printf 一样,scanf 接受一个格式字符串,指定要读入的值的个数和类型(例如 "%d" 指定读入一个 int 值)。scanf 函数在读入数值时会跳过前后的空白字符,因此它的格式字符串只需包含一串格式化占位符,占位符之间通常不需要空白或其他格式字符。格式字符串中各占位符对应的参数,指定的是读入的值要存入的程序变量的位置。在变量名前加上 & 运算符,得到的就是该变量在程序内存中的位置——变量的内存地址。第 2 章的「指针」一节会更详细地讨论 & 运算符。目前我们只在 scanf 函数中使用它。

Like printf, scanf takes a format string that specifies the number and types of values to read in (for example, "%d" specifies one int value). The scanf function skips over leading and trailing whitespace as it reads in a numeric value, so its format string only needs to contain a sequence of formatting placeholders, usually with no whitespace or other formatting characters between the placeholders in its format string. The arguments for the placeholders in the format string specify the locations of program variables into which the values read in will be stored. Prefixing the name of a variable with the & operator produces the location of that variable in the program’s memory — the memory address of the variable. The “Pointers” section in Chapter 2 discusses the & operator in more detail. For now, we use it only in the context of the scanf function.

下面是另一个 scanf 示例,其格式字符串中有两个值的占位符,第一个是 int,第二个是 float:

Here’s another scanf example, in which the format string has placeholders for two values, the first an int and the second a float:

scanf_ex.c

scanf_ex.c

1
2
3
4
5
6
7
int x;
float pi;

// read in an int value followed by a float value ("%d%g")
// store the int value at the memory location of x (&x)
// store the float value at the memory location of pi (&pi)
scanf("%d%g", &x, &pi);

通过 scanf 向程序输入数据时,各个数值输入值之间必须至少用一个空白字符隔开。不过,由于 scanf 会跳过额外的前后空白字符(例如空格、制表符和换行符),用户可以在每个输入值前后加任意多的空白。例如,对于上例中的 scanf 调用,如果用户输入下面的内容,scanf 会读入 8 并存入变量 x,然后读入 3.14 并存入变量 pi:

When inputting data to a program via scanf, individual numeric input values must be separated by at least one whitespace character. However, because scanf skips over additional leading and trailing whitespace characters (for example, spaces, tabs, and newlines), a user could enter input values with any amount of space before or after each input value. For instance, if a user enters the following for the call to scanf in the preceding example, scanf will read in 8 and store it in the x variable, and then read in 3.14 and store it in the pi variable:

1
8                   3.14