结构体
#include <stdio.h>
4
5 #define MAXTITL 40
6 #define MAXAUTL 40
7 #define MAXBKS 4 /* maximum number of books */
8
9 struct book { /* set up book template */
10 char title[MAXTITL];
11 char author[MAXAUTL];
12 float value;
13 };
14
15 int main(void)
16 {
17 struct book library[MAXBKS]; /* array of book structures */
18 int count = 0;
19 int index;
20
21 printf("Please enter the book title.\n");
22 printf("Press [enter] at the start of a line to stop.\n");
23 while (count < MAXBKS && gets(library[count].title) != NULL
24 && library[count].title[0] != '\0')
25 {
26 printf("Now enter the author.\n");
27 gets(library[count].author);
28 printf("Now enter the value.\n");
29 scanf("%f", &library[count++].value);
30 / while (getchar() != '\n')
31 / continue; // [> clear input line <]
32 /*getchar();*/
33 if (count < MAXBKS)
34 printf("Enter the next title.\n");
35 }
36
37 if (count > 0)
38 {
39 printf("Here is the list of your books:\n");
40 for (index = 0; index < count; index++)
41 printf("%s by %s: $%.2f\n", library[index].title,
42 library[index].author, library[index].value);
43 }
44 else
45 printf("No books? Too bad.\n");
46
47 return 0;
48 }
23,24行 :
gets函数读入字符串,接收到EOF或者换行符结束,读取的换行符被转换成’\0‘ 空字符
gets的null有2种情况
1.feof ( end-of-file)
2.ferror ( read error)
输完value,回车第二次就会使title[0] = '\0' ,会直接结束。
30,31行:
吸收上一个回车,防止被下一个title读入
代码来源:c primer plus 383页