#include <stdio.h>
#include <stdlib.h>
struct Date {
int year;
int month;
int day;
};
struct Book {
char title[128];
char author[40];
//float price[20];
float price;
struct Date date;
char publisher[40];
struct Book *next;
} book;
//void getInput(struct Book *book);
void getInput(struct Book *book) {
printf("请输入书名:");
scanf("%s", book->title);
printf("请输入作者:");
scanf("%s", book->author);
printf("请输入价格:");
//scanf("%f", &book->price);
//scanf("%f", book->price);
scanf("%f", &book->price);
printf("请输入日期:");
// 输入呢?
scanf("%d-%d-%d", &book->date.year, &book->date.month, &book->date.day);
printf("请输入出版社:");
scanf("%s", book->publisher);
}
//void addBook(struct Book **library);
void addBook(struct Book **library) {
//struct Book *book, *temp;
struct Book *book;
//book = (struct Book *)malloc(sizeof(struct Book));
book = malloc(sizeof(struct Book));
if(book == NULL) {
printf("内存分配失败!\n");
exit(1);
}
getInput(book);
/*
if(*library != NULL) {
temp = *library;
*library = book;
book->next = temp;
} else {
*library = book;
book->next = NULL;
}
*/
book->next = *library;
*library = book;
}
void printLibrary(struct Book *library) {
struct Book *book;
int count = 1;
book = library;
while(book != NULL) {
printf("Book%d:\n", count);
printf("书名:%s\n", book->title);
printf("作者:%s", book->author);
//printf("价格:%.2f", book->price);
//printf("价格:%.2f", book->price[0]);
printf("价格:%.2f", book->price);
//printf("日期:%d-%d-%d", book.date.year, book.date.month, book.date.day);
printf("日期:%d-%d-%d", book->date.year, book->date.month, book->date.day);
printf("出版社:%s", book->publisher);
book = book->next;
count++;
}
printf("\n");
}
/*
void releaseLibrary(struct Book *library) {
while(library != NULL) {
free(library);
library = library->next;
}
}
*/
void releaseLibrary(struct Book *library) {
if(!library) return;
releaseLibrary(library->next);
free(library);
}
int main(void) {
struct Book *library = NULL;
int ch;
while(1) {
printf("请问是否要录入书籍信息(Y/N):");
do {
ch = getchar();
} while(ch != 'Y' && ch != 'N');
if(ch == 'Y') {
addBook(&library);
} else {
break;
}
}
printf("请问是否需要打印图书馆信息(Y/N):");
do {
ch = getchar();
} while(ch != 'Y' && ch != 'N');
if(ch == 'Y') {
printLibrary(library);
}
releaseLibrary(library);
return 0;
}
|