第 9 / 187 篇

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

说明

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

1.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.

1.2.1. printf

1.2.1. printf

C 的 printf 函数与 Python 的格式化打印非常相似:调用者指定一个要打印的格式字符串。格式字符串中通常含有格式说明符,比如用来打印制表符(\t)或换行符(\n)的特殊字符,或者输出中代表某个值的占位符。占位符由 % 加一个类型说明字母组成(例如 %d 表示一个整数值的占位符)。格式字符串中的每个占位符,printf 都需要一个对应的额外参数。表 1 给出了一个带格式化输出的 Python 和 C 示例程序:

C’s printf function is very similar to formatted print in Python, 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 Python and C with formatted output:

表 1. Python 与 C 的打印语法对比

Table 1. Syntax Comparison of Printing in Python and C

Python 版本

Python version

1
2
3
4
5
6
7
8
9
10
11
# Python formatted print example


def main():

print("Name: %s, Info:" % "Vijay")
print("\tAge: %d \t Ht: %g" %(20,5.9))
print("\tYear: %d \t Dorm: %s" %(3, "Alice Paul"))

# call the main function:
main()

C 版本

C version

1
2
3
4
5
6
7
8
9
10
11
12
/* C printf example */
#include <stdio.h> // needed for printf

int main(void) {

printf("Name: %s, Info:\n", "Vijay");
printf("\tAge: %d \t Ht: %g\n",20,5.9);
printf("\tYear: %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 的 printf 与 Python 的 print 函数的主要区别在于:Python 版本会在输出字符串末尾隐式地打印一个换行符,而 C 版本不会。因此,本例中的 C 格式字符串在末尾加了换行符(\n),以显式地打印换行。在 C 的 printf 和 Python 的 print 函数中,为格式字符串里的占位符列出参数值的语法也略有不同。

The main difference between C’s printf and Python’s print functions are that the Python version implicitly prints a newline character at the end of the output string, but the C version does not. As a result, the C format strings in this example have newline (\n) characters at the end to explicitly print a newline character. The syntax for listing the argument values for the placeholders in the format string is also slightly different in C’s printf and Python’s print functions.

C 使用与 Python 相同的格式化占位符来指定不同类型的值。上面的示例演示了以下格式化占位符:

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

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

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

C additionally supports the %c placeholder for printing a character value. This 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

1.2.2. scanf

1.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.

Python 和 C 读取输入的方式不同:Python 用 input 函数把一个值读成字符串,然后由程序把字符串值转换为 int;而 C 用 scanf 读入一个 int 值,并把它存放到某个 int 程序变量所在的内存位置(例如 &num1)。表 2 给出了用 Python 和 C 读取用户输入值的示例程序:

Reading input is handled differently in Python and C: Python uses the input function to read in a value as a string, and then the program converts the string value to an int, whereas C uses scanf to read in an int value and to store it at the location in memory of an int program variable (for example, &num1). Table 2 displays example programs for reading user input values in Python and C:

表 2. Python 与 C 读取输入值的方法对比

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

Python 版本

Python version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Python input example


def main():


num1 = input("Enter a number:")
num1 = int(num1)
num2 = input("Enter another:")
num2 = int(num2)

print("%d + %d = %d" % (num1, num2, (num1+num2)))

# call the main function:
main()

C 版本

C version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* 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 的两个坑

  • 准确地说,%d、%g 这类数值转换说明会跳过输入中前导的空白字符;读完数字后,后面的空白(包括回车产生的换行符)会留在输入缓冲区里,等待下一次读取。这在混用 scanf 和按行读取的函数时常常导致「输入被跳过」的问题。
  • printf 的 %g/%f 既能打印 float 也能打印 double(float 参数会被自动提升为 double);但 scanf 不同:%f/%g 只能读入 float,读入 double 必须用 %lf。把 %f 用在 double 变量上是初学者的常见错误。

下面是另一个 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