- #1
gruba
- 206
- 1
Homework Statement
I have the following code which manipulates with basics of structures.
There are function like reading and sorting data from structures.
Now, I don't know how to write a function that reads name and surname of an author of a book,
and then prints data about books that are from read author.
Prototype of a function is
Code:
void print(BOOK *pb,int n,char *p_surname,char *p_name)
Homework Equations
-Structures
-Pointers
The Attempt at a Solution
Code:
#include <stdio.h>
#include<stdlib.h>
typedef struct
{
char surname[20];
char name [20];
}AUTHOR;
typedef struct
{
char title[20];
int year;
int number_of_authors;
AUTHOR *author;
}BOOK;
void read_author(AUTHOR *pa)
{
printf("surname:");
scanf("%s",pa->surname);
printf("name:");
scanf("%s",pa->name);
}
void read_book(BOOK *pb)
{
printf("title:");
scanf("%s",pb->title);
printf("publish year:");
scanf("%d",&pb->year);
printf("number of authors:");
scanf("%d",&pb->number_of_authors);
pb->author=calloc(pb->number_of_authors,sizeof(*pb->author));
int i;
for(i=0;i<pb->number_of_authors;i++)
{
printf("%d. authors:\n",i+1);
read_author(pb->author+i);
}
}
int compare_authors(AUTHOR *a,AUTHOR *b)
{
int i;
for(i=0;a->surname[i] && a->surname[i] == b->surname[i];i++);
return a->surname[i]-b->surname[i];
}
void sort_authors(AUTHOR *array,int n)
{
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(compare_authors(array+i,array+j)>0)
{
AUTHOR temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
int compare_books(BOOK *a,BOOK *b)
{
int i;
for(i=0;a->title[i] && a->title[i] == b->title[i];i++);
return a->title[i]-b->title[i];
}
void sort_books(BOOK *array,int n)
{
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(compare_books(array+i,array+j)>0)
{
BOOK temp=array[i];
array[i]=array[j];
array[j]=temp;
}
else
if((compare_books(array+i,array+j) == 0) )
{
BOOK temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
int main()
{
int i,n;
BOOK *array;
char psurname[101],pname[101];
do
{
printf("n=");
scanf("%d",&n);
}
while(n<1);
array=(BOOK *)malloc(n*sizeof(BOOK));
printf("enter books:\n");
for(i=0;i<n;i++)
{
printf("%d. book:\n",i+1);
read_book(array+i);
}
sort_books(array,n);
free(array);
return 0;
}
I don't know how to write a function for printing data about books that are from input author:
Code:
void print(BOOK *pb,int n,char *psurname,char *pname)
{
int i,j;
scanf("%s",psurname);
scanf("%s",pname);
for(i=0;i<n;i++)
{
for(j=0;j<pb->number_of_authors;j++)
{
if((compare_authors(pb->author[j].surname,psurname)== 0) &&
(compare_authors(pb->author[j].name,pname)==0))
printf("%s %d %d %s %s",pb->title,pb->year,pb->number_of_authors,
pb->author[j].surname,pb->author[j].name);
}
}
}
Could someone help with this function?
Thanks for replies.