首页 > 解决方案 > C 代码未按预期工作(跳过获取)

问题描述

我是 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;
}

标签: c

解决方案


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

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

改用类似的东西:

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

推荐阅读