0

The program I was trying to create was supposed to show a menu and store book details (in a structure), delete and search them. However, it seems to ignore all fgets functions. The problem probably lies in the scanf function which I used at the beginning of the code. I tried to use fgets and then atoi, but it only made my program stop working right after choosing one of the options. fgetc does not really help either (but perhaps I used it incorrectly). I do not get any error messages though.

Here is a piece of the problematic code:

struct books
{
    char title[20];
    char author[20];
    char year[10];
    char pages[10];
};

int main()
{
    struct books b[20];
    int limit = 0;
    int temp;
    int choice;
    do
    {
        printf("1 - Add a book\n2 - Delete a book\n3 - Search by year of publication\n4 - Search by author\n5 - Exit\n");
        scanf("%d", &choice);
        fflush(stdin);

        if (choice == 1)
        { 
                limit++;
                printf("Title:\n");
                fgets(b[limit].title, strlen(b[limit].title), stdin);
                printf("Author:\n");
                fgets(b[limit].author, strlen(b[limit].author), stdin);
                printf("Year of publication:\n");
                fgets(b[limit].year, strlen(b[limit].year), stdin);
                printf("Number of pages:\n");
                fgets(b[limit].pages, strlen(b[limit].pages), stdin);
                printf("Added a book.\n");
        }

Thank you all in advance.

Vicky
  • 11
  • 2
  • Always check the return value of scanf. See [this link](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html) for further information. – Andreas Wenzel Jan 11 '20 at 18:23
  • Don't mix `scanf` with `fgets`, use one method only. Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer) and [fgets doesn't work after scanf](https://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf). If you want to input a number, use `fgets` and apply `sscanf` to it. – Weather Vane Jan 11 '20 at 18:57
  • See this link on why `fflush(stdin);` should not be used: https://stackoverflow.com/questions/2979209/using-fflushstdin – Andreas Wenzel Jan 11 '20 at 19:03

0 Answers0