c - 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;
}
解决方案
fflush(stdin);/清除输入流中的任何文本/
您不应该将 fflush-function 与 stdin-stream 一起使用。这是未定义的行为。
改用类似的东西:
while (getchar() != '\n') {
// empty buffer
}
推荐阅读
- jenkins - Jenkins 报告的总计 Robot Framework 结果(所有套件)
- regex - 从文本中排除单个字符串
- java - layoutInflater.inflate() 方法无法解析 layoutName
- javascript - 如何在 JavaScript 中获取渐变颜色的十六进制代码(基于值的 3 种颜色)
- python - 从一个文件运行多个 Python 脚本
- mysql - MySQL按日期排序其中日期> =今天在升序中,然后日期<今天在1个查询中降序
- libgdx - 如何强制 OpenAL 与 libgdx 中的 pulseaudio 交互?(适用于 GNOME,但不适用于 i3)
- python-3.x - 从先前训练的模型 Tensorflow 预测
- codenameone - GUI Builder 中的 Cant design 对话框
- c# - Wordpress 5.2.2 和 selenium:无法找到正文帖子(不在 iframe 或 TinyMCE 中的富文本编辑器)