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.
Your first scanf
call fails if you do not exactly type in the $ before the amount. As a result, scanf
immediately returns, and the second scanf
reads the input that should have went to the previous scanf
call.
Edit: Sorry, I didn't provide the source for the information. According to the man page for scanf(3):
The format string consists of a sequence of directives which describe how to process the sequence of input characters. If processing of a directive fails, no further input is read, and scanf() returns. A "failure" can be either of the following: input failure, meaning that input characters were unavailable, or matching failure, meaning that the input was inappropriate (see below).
Change like this
for(ctr = 0; ctr < 3; ctr++)
{
printf("What is the name of the book #%d?\n", (ctr+1));
gets(books[ctr].title);
puts("Who is the author? ");
gets(books[ctr].author);
puts("How much did the book cost? ");
scanf("%lf$", &books[ctr].price); //Changed
puts("How many pages in the book? ");
scanf(" %d", &books[ctr].pages);
getchar(); // Clears last newline for the next loop
}
scanf man page
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 <stdio.h>
#include <stdlib.h>
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