我正在尝试在C中创建一个简单的链接列表。但程序只是跳过" 输入更多节点?[y / n] "部分。 这是我的计划:
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
}*start = NULL;
void createlist()
{
int item;
char choice = 'y';
struct node *newNode;
struct node *current;
while(choice != 'n')
{
printf("Enter item to add in the Linked List\n\n");
scanf("%d", &item);
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = item;
newNode->next = NULL;
if(start == NULL)
{
start = newNode;
current = newNode;
}
else
{
current->next = newNode;
current = newNode;
}
printf("Enter more nodes?[y/n]\n");
scanf("%c", &choice);
}
}
void display()
{
struct node *new_node;
printf("Your node is :\n");
new_node = start;
while(new_node!=NULL)
{
printf("%d ---> ", new_node->data );
new_node = new_node->next;
}
}
int main()
{
createlist();
display();
return 0;
}
输出: Program skipping choice input part
但是当我从 char 更改选择变量 int 时,程序运行完美。 这是工作职能:
void createlist()
{
int item;
int choice = 1;
struct node *newNode;
struct node *current;
while(choice != 0)
{
printf("Enter item to add in the Linked List\n\n");
scanf("%d", &item);
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = item;
newNode->next = NULL;
if(start == NULL)
{
start = newNode;
current = newNode;
}
else
{
current->next = newNode;
current = newNode;
}
printf("Enter more nodes?\n[NO - 0, YES - 1]\n");
scanf("%d", &choice);
}
}
当选择是 char 类型时,你能告诉我为什么程序工作不正常吗?
答案 0 :(得分:1)
输入缓冲区中剩余newline
,正在为%c
格式读取。变化
scanf("%c", &choice);
到
scanf(" %c", &choice);`
前导空格告诉scanf
先清除空白。这会自动以%d
格式发生。