【问题标题】:Function fgets doesn't store string函数 fgets 不存储字符串
【发布时间】:2019-06-01 12:44:12
【问题描述】:

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

#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("请输入你的名字:") 中的内容; 并忽略以下行( fgets(persons[i].f_name..) , 之后直接进入程序结束 请帮忙

【问题讨论】:

  • 好的,我明白了,谢谢
  • 贴出的代码无法编译!您希望我们如何重现该问题,以便我们可以帮助您调试它。请发帖minimal reproducible example

标签: c arrays pointers filesystems


【解决方案1】:

避免在同一个流上同时使用fgets() 和scanf()。

在scanf("%d", &amp;answer) 读取数字文本并形成int 后,以下Enter 或'\n' 仍保留在stdin 中。 @xing

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


各种解决方案:

A) 在scanf("%d", &amp;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():int my_get_int(int *i)

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

【讨论】:

  • 先生,我已经看到了你很多精彩的答案。你能看看stackoverflow.com/questions/54076333/…吗??
  • @chux 我更了解 scanf 和 fgets 是如何工作的,谢谢。我尝试了你所有的解决方案,它们都在工作,但你能解释一下 A 和 C 的吗?
  • @TonyStark A) 示例:您输入 4 个键 "123\",scanf("%d", &amp;answer); 将消耗 "123",留下 "\n" 用于下一个输入操作。紧随其后的fgets() 会将当时剩下的短行读取为"\n"。如果介于两者之间,则代码执行 A),然后读取 "123" 之后直到并包括 "\n" 的所有字符 - 并丢弃。那么下面的fgets() 将不会得到“\n”`,而是读入下一行输入(名字)。
  • @TonyStark C) 请参阅linked answer 并在此处评论所需的任何详细信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-01
  • 1970-01-01
  • 2021-05-31
  • 2022-12-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
相关资源
最近更新 更多