【发布时间】: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.his deprecated,所以不要使用它。 请不要使用very dangerous and obsoletegetsfunction。另外,fflush(stdin)results in undefined behavior。 -
你的代码太长了,我刚才看不懂,但如果你用
scanf读一些输入,用fgets(或gets)读其他,就不行工作。scanf倾向于将\n留在输入缓冲区中,下次您尝试使用fgets(或gets)读取一行时,您会得到剩余的\n,它看起来像一个空行。 -
你在哪里学会使用
gets()?
标签: c