Hi I was trying to implement a library system using C. I defined an abstract type of data called Book with the following fields:
typedef char StringBook [MAX_LEN];
typedef char ISBN [ISBN_LEN];
typedef struct {
StringBook title; /// Title of the book
StringBook author; /// Author
StringBook editorial; /// Editorial
ISBN isbn; /// ISBN
int date; /// Publication year
int num; /// Number of copies
}Book;
I defined several functions to set and get the fields of the structure.
In addition in the main function I defined a function, that creates a new book with the data introduced by the keyboard.
void
introduce_book_details(Book* book){
StringBook string;
ISBN isbn;
int date;
fprintf(stdout, "\nIntroduce the book details: ");
fprintf(stdout, "\n\nTitle: ");
fgets(string, MAX_LEN, stdin);
delete_char(string);
fflush(stdin);
set_title(book, string);
fprintf(stdout, "Author: ");
fgets(string, MAX_LEN, stdin);
delete_char(string);
fflush(stdin);
set_author(book, string);
fprintf(stdout, "Editorial: ");
fgets(string, MAX_LEN, stdin);
delete_char(string);
fflush(stdin);
set_editorial(book, string);
fprintf(stdout, "ISBN: ");
fgets(isbn, MAX_LEN, stdin);
delete_char(isbn);
set_isbn(book, isbn);
fprintf(stdout, "Date: ");
fscanf(stdin, "%d", &date);
fflush(stdin);
set_date(book, date);
set_num(book, 1);
}
So far so good. In the main function I create a book and call introduce_book_details and works. The problem comes if I use the function fscanf before. For instance, I want to create a menu with several options from 1 to 8. The option is introduced by the keyboard, and if it is 1, then the function introduce_book_details is called. However if I introduce this in the main function as:
int main() {
Book book;
int option;
fprintf(stdout, "Introduce the option: ");
fscanf(stdin, "%d", &option);
fflush(stdin);
if(option == 1) {
introduce_book_details(&book);
print_book(book);
}
return 0;
}
Then the console shows this:
Introduce the option: 1
Introduce the book details:
Title: Author:
Meaning that the I am not able to introduce the title and the first field I can introduce is the author (being title, NULL). If in the main function I remove the lines to introduce an option by keyboard the program works good. So I believe this has something to do with the fscanf or fflush functions. Any tip or help is welcome. Thanks beforehand.