为什么我不能在链表中输入多个条目?

时间:2015-05-07 16:13:43

标签: c data-structures linked-list

我是C的新手,我正在尝试学习链表,但出于某种原因,我不能给出多个值。程序在给出一个值后结束。 这是我的代码:

#include<stdio.h>
#include<stdlib.h>
typedef struct node_type {
    int data;
    struct node_type *next;
} node;

int main()
{
    typedef node *list;
    list head, temp;
    char ch;
    int n;
    head = NULL;
    printf("enter Data?(y/n)\n");
    scanf("%c", &ch);

    while ( ch == 'y' || ch == 'Y')
    {
        printf("\nenter data:");
        scanf("%d", &n);
        temp = (list)malloc(sizeof(node));
        temp->data = n;
        temp->next = head;
        head = temp;
        printf("enter more data?(y/n)\n");

        scanf("%c", &ch);

    }
    temp = head;
    while (temp != NULL)
    {
        printf("%d", temp->data);
        temp = temp->next;
    }

    return 0;
}

1 个答案:

答案 0 :(得分:1)

将此更改:scanf("%c", &ch);更改为此scanf(" %c", &ch);

您的代码未接受任何输入的原因是scanf消耗了缓冲区中的换行符。 %c之前的空格会导致scanf()在读取预期字符之前跳过缓冲区中的空格和换行符。

Working code