C Primer Plus 第十四章 编程练习3

作者在 2013-05-16 12:52:47 发布以下内容
/*
修改程序清单14.2中的书目列表程序
使它首先按照输入的顺序输出图书的描述
然后按照标题的字母升序输出图书的描述
最后按照value值的升序输出图书的描述 
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXTITL 40	/*书名*/
#define MAXAUTL 40	/*作者名*/
#define MAXBKS 100	/*最多可以容纳的图书数*/

typedef struct{
	char title[MAXTITL];
	char author[MAXAUTL];
	float value;
} BOOKS;

void clearcache(void);
void display_default(const BOOKS *, const int);
void display_title_asc(BOOKS *, const int);
void display_value_asc(BOOKS *, const int);

int main(void)
{
	BOOKS library[MAXBKS];
	int count = 0;
	
	printf("Please enter the book title.\n");
	printf("Press [enter] at the start of a line to stop.\n");
	
	while(count < MAXBKS && gets(library[count].title) != NULL && library[count].title[0] != '\0')
	{
		printf("Now enter the author.\n");
		gets(library[count].author);
		printf("Now enter the value.\n");
		scanf("%f", &library[count].value);
		clearcache();
		
		if(count < MAXBKS)
			printf("Enter the next title.\n");
		count++;
	}
	
	if(count > 0)
	{
		display_default(library, count);
		display_title_asc(library, count);
		display_value_asc(library, count);
	}
	else
		printf("No books? Too bad.\n");
		
	return 0;
}

void display_value_asc(BOOKS * pts, const int count)
{
	int i, j;
	BOOKS temp;
	for(i = 0; i < count - 1; i++)
		for(j = i + 1; j < count; j++)
		{
			if(pts[i].value > pts[j].value)
			{
				temp = pts[i];
				pts[i] = pts[j];
				pts[j] = temp;
			}
		}
	printf("Here is the list of your books (by value ASC): \n");
	for(i = 0; i < count; i++, pts++)
		printf("%s by %s: $%.2f\n",
			pts->title, pts->author, pts->value);
}
void display_title_asc(BOOKS * pts, const int count)
{
	int i, j;
	BOOKS temp;
	
	for(i = 0; i < count - 1; i++)
		for(j = i + 1; j < count; j++)
		{
			if(strcmp(pts[i].title, pts[j].title) > 0)
			{
				temp = pts[i];
				pts[i] = pts[j];
				pts[j] = temp;
			}
		}
	printf("Here is the list of your books (by title ASC): \n");
	for(i = 0; i < count; i++, pts++)
		printf("%s by %s: $%.2f\n",
			pts->title, pts->author, pts->value);
}

void display_default(const BOOKS * pts, const int count)
{
	int i;
	
	printf("Here is the list of your books (by default): \n");
	for(i = 0; i < count; i++, pts++)
		printf("%s by %s: $%.2f\n",
			pts->title, pts->author, pts->value);
}

void clearcache(void)
{
	while(getchar() != '\n')
		continue;
}
文章评论,共0条
游客请输入验证码
浏览39543次