1

I am new to C and I'm trying to learn linked list but for some reason I can't give more than one value. The program ends after giving one value. Here is my code:

#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;
}
Mgetz
  • 5,108
  • 2
  • 33
  • 51
Eddie023
  • 106
  • 8

1 Answers1

1

Change this : scanf("%c", &ch); to this scanf(" %c", &ch);

The reason that your code did not take any input was because the scanf consumed the newline from the buffer. The blank space before %c causes scanf() to skip white space and newline from the buffer before reading the character intended.

Working code

Ayushi Jha
  • 4,003
  • 3
  • 26
  • 43