gpt4 book ai didi

c - 在链表中输入元素时进行迭代

转载 作者:行者123 更新时间:2023-11-30 15:06:18 26 4
gpt4 key购买 nike

我正在尝试用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

但是当我将 choice 变量从 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);
}
}

你们能告诉我为什么当choicechar类型时程序无法正常工作吗?

最佳答案

输入缓冲区中有一个换行符,正在以%c 格式读取。改变

scanf("%c", &choice);

scanf(" %c", &choice);`

前导空格告诉 scanf 首先清除空格。使用 %d 格式时会自动发生。

关于c - 在链表中输入元素时进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39189054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com