Vaibhav Vats Vaibhav Vats - 3 months ago 17
C Question

Iteration while entering elements in linked list

I am trying to make a simple linked list in C. But program just skips the input of " Enter more nodes?[y/n]" part.
Here's my program:

#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;
}


Output:
Program skipping choice input part

But when I change choice varaiable to int from char, program runs perfectly.
Here's the working function:

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);
}
}


Can you guys please tell me why program works incorrectly when choice is char type?

Answer

There is a newline left in the input buffer which is being read for the %c format. Change

scanf("%c", &choice);

to

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

The leading space tells scanf to clean off whitespace first. This happens automatically with the %d format.