【问题标题】:C code not working as intended(skipped gets)C 代码未按预期工作(跳过获取)
【发布时间】:2021-02-17 12:26:08
【问题描述】:

我是 C 的新手,我正在尝试对此进行类似的编码。 但由于某种原因gets,要求新记录的名称不断被跳过。

/* Define libraries to be included */
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <ctype.h>

/* Define Structures*/
typedef struct contact {
    int number;        /*unique account number*/
    char name[20];     /*contains name*/
    char phone[15];    /*contains phone number*/
    char email[20];           /*contains email address*/
    struct contact *next; /*next is used to navigate through structures.*/
    int count;     /*count is used to input comments into array*/
} Contact;
void addNewContact(void) /* add new contact function*/
{
    newRecord = (struct contact*)malloc(sizeof(struct contact));
    if (firstRecord == NULL) {
        firstRecord = currentRecord = newRecord;
    }
    else {
        currentRecord = firstRecord;     
        while (currentRecord->next != NULL)currentRecord = currentRecord->next;
        currentRecord->next = newRecord; 
        currentRecord = newRecord;        
    }
    currentRecordNumber++;
    printf("%27s: %5i\n", "contact number", currentRecordNumber);
    currentRecord->number = currentRecordNumber;   
    fflush(stdin);
    printf("Enter contact name");
    gets(currentRecord->name);/*this got skipped(no input asked)*/
    fflush(stdin);
    printf("Enter contact Phone number");
    gets(currentRecord->phone);
    fflush(stdin);
    printf("Enter contact email");
    gets(currentRecord->email);
    fflush(stdin);
    printf("contact added!");
    currentRecord->count = 0;
    currentRecord->next = NULL;
}

【问题讨论】:

  • 请创建一个minimal, reproducible example。代码太长了。
  • 上面提到的代码太多,所以任何人都很难代表您轻松发现确切的错误。一些建议:malloc.h is deprecated,所以不要使用它。 请不要使用very dangerous and obsolete gets function另外,fflush(stdin) results in undefined behavior
  • 确保一切都已初始化,检查scanf的返回值,检查malloc的返回值,使用一些必要的编译标志编译你的代码,例如-Wall -Werror -Wextra -O2 -g如果使用@ 987654335@/clang 并解决报告的所有错误。考虑使用valgrindgdb 来调试您的代码。
  • 你的代码太长了,我刚才看不懂,但如果你用scanf读一些输入,用fgets(或gets)读其他,就不行工作。 scanf 倾向于将\n 留在输入缓冲区中,下次您尝试使用fgets(或gets)读取一行时,您会得到剩余的\n,它看起来像一个空行。
  • 你在哪里学会使用gets()

标签: c


【解决方案1】:

fflush(stdin);/从输入流中清除任何文本/

您不应该将 fflush-function 与 stdin-stream 一起使用。这是未定义的行为。

改用类似的东西:

  while (getchar() != '\n') {
      // empty buffer
   }

【讨论】:

  • 刷新输入流不仅是 OP 代码中的问题。
  • 当然不是,但是他一直在调用这个函数。
  • 这是一个评论,而不是一个答案。
  • 重点是:问题不在于使用fflush(stdin)刷新输入。问题是试图刷新输入。如果你发现自己需要在这样的程序中刷新输入,这总是因为scanf 的使用不当,可能是因为它与fgets(或gets)等行读取函数混合在一起。修复scanf的用法,完全不需要刷新输入。
  • @SteveSummit 修复 scanf 用法的一个好方法是改用 fgetssscanf
猜你喜欢
  • 1970-01-01
  • 2016-07-06
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-26
  • 2020-11-01
相关资源
最近更新 更多