I\'m learning about data structures. I\'ve written a simple program that asks the user to fill in information on a 3 book purchase. Like name of book, author, cost and pages.
i edited your code by using file processing functions. and it is a good way since it omits all the invalid inputs the user may enter after its answers. like:
75467 jhfjkghsj;kfjgklj
here is your edited code:
struct bookinfo {
char title[40];
char author[25];
double price;
int pages;
}; // Header File "bookinfo"
#include
#include
int main(void)
{
int ctr;
struct bookinfo books[3]; // Array of three structure variables
// Get the information about each book from the user
for(ctr = 0; ctr < 3; ctr++)
{
printf("What is the name of the book #%d?\n", (ctr+1));
gets(books[ctr].title);
fseek(stdin,0,SEEK_END);
puts("Who is the author? ");
gets(books[ctr].author);
fseek(stdin,0,SEEK_END);
puts("How much did the book cost? ");
scanf(" $%f", &books[ctr].price);
fseek(stdin,0,SEEK_END);
puts("How many pages in the book? ");
scanf(" %d", &books[ctr].pages);
fseek(stdin,0,SEEK_END);
}
// Print a header line and then loop through and print the info
printf("\n\nHere is the collection of books: \n");
for(ctr = 0; ctr < 3; ctr++)
{
printf("#%d: %s by %s", (ctr+1), books[ctr].title, books[ctr].author);
printf("\nIt is %d pages and cost $%.2f", books[ctr].pages, books[ctr].price);
printf("\n\n");
}
return (0);
}
I've added the fseek function after every input. this function moves the file pointer to the place you want. here, 0 offset from the end of stdin