我正在尝试收集用户输入,但我的"标题"正在逐渐消失.如果我评论"评级"和"年份"的fgets,它不会被消灭.我不明白为什么?
另外,使用fgets时我的int输出不正确(参见输出).但如果我使用scanf就是.这是为什么?
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);
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
MAIN.C
#include "movie.h"
int main(){
movie_t movie;
movie.year = 0;
get_movie(&movie);
print_movie(&movie);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
标题:蝙蝠侠
进入导演名称:斯皮尔伯格
输入电影评级:R
输入电影年份:2000
职务:
董事:Spielberg
评级:R
年份:808464434
看这个:
#define SIZE_LIMIT 25
// ^^
fgets(&mvi->title, 50, stdin);
// ^^
Run Code Online (Sandbox Code Playgroud)
只需使用SIZE_LIMIT而不是50.
(您也应该使用mvi->title或&mvi->title[0]代替&mvi->title,否则您会遇到类型错误......您是否包含正确的标题?)
而且,这些都是完全错误的:
fgets(&mvi->rating,5, stdin);
fgets(&mvi->year, 5, stdin);
Run Code Online (Sandbox Code Playgroud)
你可能想要使用scanf()或者其他东西.该fgets()函数读取字符串,但既不是字符串rating也不year是字符串.这就是为什么scanf()正常工作,因为你可以scanf()用来读取整数.
因为808464434是字符串"2000",解释为整数,0x30303032.0x30是ASCII中的字符"0",0x32是ASCII中的字符"2".