0

Every time I try to use an array of structs and get the input from the users it skips a scanf and I can't figure out why. I simplified the code by making the array of only 1 element and scanning just for that element and not with a for loop, but it still doesn't work.

#include <stdio.h>
#include <string.h>

int main(){

  typedef struct {
    char title[30];
    char author[30];
    int year;
  } Books;

  Books library[1]; //array of structs

  //input
    printf("\nAdd a new book to the shelf");
    printf("\nTitle: ");
    scanf("%[^\n]",library[0].title);
    printf("\nAuthor: ");
    scanf("%[^\n]",library[0].author);
    printf("\nYear: ");
    scanf("%d",&library[0].year);

  //print
    printf("\nTitle: ");
    printf("%s",library[0].title);
    printf("\nAuthor: ");
    printf("%s",library[0].author);
    printf("\nYear: ");
    printf("%d\n",library[0].year);

    return 0;
}

terminal:

Add a new book to the shelf
Title: Fist Book  //input by user

Author:                 //doesn't let me scan anything and jumps to Year: 
Year: 1998 //input

Title: Fist Book 
Author: 
Year: 1998
thep1rate
  • 45
  • 1
  • 7
  • 2
    `"%[^\n]"` doesn't skip whitespace. Try `" %[^\n]"`. – user3386109 Jul 30 '19 at 18:08
  • 1
    That's not an array of structs. That's a *single* struct. You may want to name your book structure `Book` not `Books` as it's just one, not many. – tadman Jul 30 '19 at 18:09
  • @user3386109 Thank you so much! That actually worked, but I'm not sure why. Could you explain the difference please? – thep1rate Jul 30 '19 at 18:27
  • 1
    The link in the yellow box at the top of your question leads to a duplicate question. The answers to that question explain what the space does, and provide alternative solutions to the problem. – user3386109 Jul 30 '19 at 18:33

1 Answers1

2

In scanf, %[^\n] doesn't skip whitespace. To skip whitespace (which should fix your issue), do this:

scanf(" %[^\n]", library[num].member);
S.S. Anne
  • 13,819
  • 7
  • 31
  • 62