总共打印三次图书目录信息
第一次,是直接按输入的顺序进行输出打印。
第二次,按字母排序,通过strcmp()函数比较,通过新建的临时int变量,对编号进行重新赋值,再通过循环比较编号进行排序。
第三次,按书本金额排序,引入了一个临时结构,通过临时结构来对两个结构进行数据的交换,然后打印。
# include <stdio.h> # include <string.h> # define MAXTITL 40 # define MAXAUTL 40 # define MAXBKS 100 struct book { int num; //编号 char title[MAXTITL]; char author[MAXAUTL]; float value; }; struct book library[MAXBKS]; char* s_gets(char* st, int n);
void show_list(struct book library[], int n); //按输入顺序 void show_letter(struct book library[], int n); //按字母顺序 void show_value(struct book library[], int n); //按金额升序 int main() { int count = 0; struct book * pt; pt = &library[0]; printf("Please enter the book title:\n"); printf("Press [enter] at the start of a line to quit.\n"); while (count <= MAXBKS && s_gets(library[count].title, MAXTITL) != NULL && library[count].title[0] != '\0') { puts("Enter the author:"); s_gets(library[count].author, MAXAUTL); puts("Enter the value:"); scanf("%f",&library[count].value); while (getchar() != '\n') continue; //清理输入行 library[count++].num = count; if (count < MAXBKS) printf("PLease enter next title:\n"); } if (count > 0) { puts("According to the entry sequence:"); show_list(pt,count); puts("According to the first letter of the book_title:"); show_letter(pt, count); puts("According to the value of the book:"); show_value(pt, count); } else
puts("No book."); return 0; } void show_list(struct book library[],int n) { for (int i = 0; i < n; i++) printf("%d : %s by %s : $ %.2f\n",library[i].num, library[i].title, library[i].author,library[i].value); } void show_letter(struct book library[], int n) { int temp; //临时变量 int k = 0; for (int i = 0; i < n; i++) for(int j = i+1;j < n ;j++) { if (strcmp(library[i].title, library[j].title) > 0) { temp = library[i].num; library[i].num = library[j].num; library[j]. num = temp; } } while(k < n ) { for (int i = 0; i < n; i++) { if (library[i].num == k) printf("%d :%s by %s : %.2f\n", library[i].num, library[i].title, library[i].author, library[i].value); } k++; } } void show_value(struct book library[], int n) { struct book temp; for(int i = 0;i < n;i++) for (int j = i + 1; j < n; j++) { if (library[i].value > library[j].value) { struct book temp = library[i]; library[i] = library[j]; library[j] = temp; } } for(int k = 0;k<n;k++) printf("%d : %s by %s : $ %.2f\n", library[k].num, library[k].title, library[k].author, library[k].value); } char* s_gets(char* pt, int n) { char* ret_val; char* find; ret_val = fgets(pt, n, stdin); if (ret_val) { find = strchr(pt, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; }