-2

I want to make a program with struct which prints out the data of a film entered by the user. The program looks like this:

#include <stdio.h>
#include <stdlib.h>

struct films {
  char title[100];
  int length;
  char genre[100];
};

int main() {
  int n;
  scanf("%d",&n);

  struct films film[100];
  for (int i=0; i<n; i++) {
    printf("%d. film:\n", i+1);
    printf("Title: ");
    fgets(film[i].title,100,stdin);
    printf("Lenght: ");
    scanf("%d",&film[i].length);
    printf("Mufaj: ");
    fgets(film[i].genre,100,stdin);
  }
  printf("The films: \n");
  for (int i=0; i<n; i++)
    printf("The %d.film:[%s:%d:%s] ", i+1 , film[i].title, film[i].length, film[i].genre);
  return 0;
}

I made a mistake at fgets, but I don't know what should I do to make it right.

Can somebody help me?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Tyler Joe
  • 357
  • 2
  • 18
  • 1
    Hello Tyler please provide some more explanation about what does not work or what errors occur with the exact error message texts. Otherwise this is a "Look at my code and fix it" post instead of "help me to resolve this specific problem i can not figure out" – Yastanub Nov 08 '18 at 14:56

2 Answers2

2

This can happen if you mix fgets with scanf.

After the scanf call to read the length, there's a newline left in the input buffer. On the following call to fgets, it reads just that newline.

Replace the scanf call with a call to fgets using a temporary string followed by sscanf:

char line[100];
fgets(line, 100, stdin);
sscanf(line, "%d",&film[i].length);
dbush
  • 205,898
  • 23
  • 218
  • 273
0

Another option, besides what @dbush mentioned, is to consume all characters after scanning for an integer:

scanf("%d",&n);
while(getchar() != '\n')
    continue;

printf("Lenght: ");
scanf("%d",&film[i].length);
while(getchar() != '\n')
    continue;

The problem is, after scanf reads an integer value, the \n' is left in the input stream. A subsequent call to fgets reads the '\n' and returns.

Another problem you have is that fgets leaves the \n in the string. When you print out the data later you get something like this:

$ ./main.exe
1
1. film:
Title: one
Lenght: 2
Mufaj: three
The films:
The 1.film:[one
:2:three
]

To resolve this issue, you can use strchr in string.h. For example:

char *ch = strchr(film[i].title, '\n');
if(ch != NULL)
    ch[0] = '\0';
Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46