【问题标题】:Why can't I enter more than one entry in my linked list? [duplicate]为什么我不能在我的链接列表中输入多个条目? [复制]
【发布时间】:2015-07-18 08:18:32
【问题描述】:

我是 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;
}

【问题讨论】:

    标签: c data-structures linked-list


    【解决方案1】:

    把这个:scanf("%c", &amp;ch);改成这个scanf(" %c", &amp;ch);

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

    Working code

    【讨论】:

    • 谢谢。现在可以使用了:D
    猜你喜欢
    • 2012-01-07
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多