mdo123 mdo123 - 2 months ago 18
C Question

C- fgets() erasing user input

I'm trying to collect user input but my "Title" is getting wiped out. If I comment out the fgets for "Rating" and "Year" it doesn't get wiped out. I don't understand why?

Also, when using fgets my int is not correct output (see output). But if I use scanf it is. Why is that?

MOVIE.C

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

void print_movie(const movie_t * mvi) {
printf("Title:%s", mvi->title);
printf("Director:%s", mvi->director);
printf("Rating:%c\n", mvi->rating);
printf("Year: %d\n", mvi->year);
}

void get_movie(movie_t * mvi) {
printf("Title:");
fgets(&mvi->title, 50, stdin);
printf("Enter Director Name:");
fgets(&mvi->director, 50, stdin);
printf("Enter Movie Rating:");
fgets(&mvi->rating,5, stdin);
printf("Enter Movie Year:");
fgets(&mvi->year, 5, stdin);
//scanf will output correct year
//scanf("%d",&mvi->year);
}


MOVIE.H

#ifndef MOVIE_H
#define MOVIE_H
#define SIZE_LIMIT 25
#define RATING_SIZE 5

typedef enum {G, PG, PG13, R} rating_t;

typedef struct {
char rating;
char title[SIZE_LIMIT];
char director[SIZE_LIMIT];
int year;
}movie_t;


void get_movie(movie_t * movie);
void print_movie(const movie_t * movie);

#endif /* MOVIE_H


MAIN.C

#include "movie.h"

int main(){
movie_t movie;
movie.year = 0;
get_movie(&movie);
print_movie(&movie);
return 0;
}



  • INPUT



Title:Batman

Enter Director Name:Spielberg

Enter Movie Rating:R

Enter Movie Year:2000



  • OUTPUT



Title:

Director:Spielberg

Rating:R

Year: 808464434

Answer

Look at this:

#define SIZE_LIMIT 25
//                 ^^

fgets(&mvi->title, 50, stdin);
//                 ^^

Just use SIZE_LIMIT instead of 50.

(You should also use mvi->title or &mvi->title[0] instead of &mvi->title, otherwise you have a type error... are you including the right headers?)

Also, these are completely wrong:

fgets(&mvi->rating,5, stdin);
fgets(&mvi->year, 5, stdin);

You'll probably want to use scanf() or something instead. The fgets() function reads strings, but neither rating nor year is a string. That's why scanf() works correctly, because you can use scanf() to read integers.

Why 808464434?

Because 808464434 is the string "2000" interpreted as an integer, 0x30303032. 0x30 is the character '0' in ASCII, and 0x32 is the character '2' in ASCII.