我是链接列表的新手,现在我在节点数量方面遇到的问题很少.
在这里,我可以填充链表的第一个节点,但该gets()函数似乎没有暂停执行以填充下一个节点.
输出如下:
Var name : var
Do you want to continue ?y
Var name : Do you want to continue ? // Here I cannot input second data
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
struct data
{
char name[50];
struct data* next;
};
struct data* head=NULL;
struct data* current=NULL;
void CreateConfig()
{
head = malloc(sizeof(struct data));
head->next=NULL;
current = head;
char ch;
while(1)
{
printf("Var name : ");
gets(current->name); //Here is the problem,
printf("Do you want to continue ?");
ch=getchar();
if(ch=='n')
{
current->next=NULL;
break;
}
current->next= malloc(sizeof(struct data));
current=current->next;
}
}
Run Code Online (Sandbox Code Playgroud)
这是因为:
ch=getchar();
Run Code Online (Sandbox Code Playgroud)
读取y或n从输入读取并分配给ch输入缓冲区中的换行符,该换行符gets将在下一次迭代中读取.
要解决此问题,您需要y/n在用户输入后使用换行符.为此,您可以添加另一个调用getchar():
ch=getchar(); // read user input
getchar(); // consume newline
Run Code Online (Sandbox Code Playgroud)
此功能也fgets应该用来代替gets.为什么?