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



我正试图在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 Listnn");
        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;
}

输出:程序跳过选择输入部分

但是当我将选择变量从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 Listnn");
        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类型时程序工作不正确吗?

输入缓冲区中还有一个newline,它正在被读取为%c格式。把

scanf("%c", &choice);

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

前导空格告诉scanf先清除空白。对于%d格式,这将自动发生。

相关内容

  • 没有找到相关文章

最新更新