函数 fgets 不存储字符串

Function fgets doesn't store string

所以我想创建一个地址簿程序,我有以下代码:

#define MAX_VALUE_FOR_ARRAYS 1000

int i = 0 ;
int answer = 0 ;
int number_of_people = 0 ;

FILE* address_book = NULL ;

address_book = fopen("addressBook.txt", "w")  ;

typedef struct People People ;

struct People
{
    char f_name[MAX_VALUE_FOR_ARRAYS]
};

People *persons = NULL ;

printf("A D D R R E S S  B O O K \n\n\n") ;

printf("1. Add a new contact \n") ;
printf("2. View all contacts \n") ;
printf("\nMake your choice : ") ;

while (answer < 1 || answer > 2)
{
    printf("\nWrong input, try again ! : ") ;
    scanf("%d", &answer) ;
}

if (answer == 1)
{
    printf("How many contacts do you want to add ? : ") ;
    scanf("%d", &number_of_people) ;

    persons = malloc(number_of_people * sizeof(People) ) ;

    if (persons == NULL)
    {
        printf("\nMemory allocation failed !") ;
    }

    for (i = 0; i < number_of_people; i++)
    {
        printf("Person %d ", (i+1)) ;
        printf("Enter the first name : ") ;
        fgets(persons[i].f_name, MAX_VALUE_FOR_ARRAYS, stdin) ;

        if (address_book == NULL)
        {
        printf("\nFailed to open file ! ") ;
        }

    fputs(persons[i].f_name, address_book) ;
    fputc('\n', address_book) ;

    }
}

我的问题是程序不想存储名字("fgets" 调用行)。 它显示 printf("Enter you first name : ") 中的内容; 并忽略以下行( fgets(persons[i].f_name..) , 之后直接进入程序末尾 请帮忙

避免在同一流中同时使用 fgets()scanf()

scanf("%d", &answer)读取数字文本后形成一个int,下面输入'\n'留在stdin .

稍后,fgets(persons[i].f_name,... 简单读取剩余的 '\n' 作为名字的输入。


各种解决方案:

A) 在 scanf("%d", &answer); 之后读取行中剩余的字符

int ch;
while ((ch = getchar()) != '\n') && ch != EOF) {
  ;
}

B) 使用fgets()阅读answer

char buf[50];
fgets(buf, sizeof buf, stdin);
answer = atoi(buf);

C) 稳健地使用 fgets()

if (my_get_int(&answer) == 1) {
  // Success
}