0

So I working on creating a function called 'Create' that asks the user to enter numbers for a linked list. If the user types in 'Y', then ask to enter another element else if the user types 'N' stop and display the linked list, but I am having a bit of trouble. When I run it, it doesn't give me the option to type in Y or N and also when I type in N, it adds a 0 to the linked list. What is happening?

#include <stdio.h>
#include <stdlib.h>

//-------------------------------------------------
struct node {
int data;
struct node *next;
}*start=NULL;
//------------------------------------------------------------

void create() {
char ch;
do {

struct node *new_node,*current;
new_node=(struct node *)malloc(sizeof(struct node));

printf("Enter the data : ");
scanf("%d",&new_node->data);
new_node->next=NULL;

if(start==NULL) {
  start=new_node;
  current=new_node;
} else {
  current->next=new_node;
  current=new_node;
}

printf("Do you want to create another?(Y\N) ");
ch = getchar();
  } while(ch!='N');
}

//------------------------------------------------------------------

void display()  {
  struct node *new_node;
  printf("The Linked List : ");
  new_node=start;

  while(new_node!=NULL) {
    printf("%d--->",new_node->data);
    new_node=new_node->next;
  }
  printf("NULL\n");
}
//----------------------------------------------------

int main() {

  create();
 display();
}
HPotter
  • 141
  • 2
  • 11
  • 1
    The `scanf` will leave a newline character in the input which the `getchar` will read. – kaylum Dec 04 '16 at 05:58
  • You should look into [proper C formatting](//prohackr112.tk/r/proper-c-formatting). Or learn how to [thoroughly obfuscate your code](//prohackr112.tk/r/proper-c-obfuscation). – MD XF Dec 04 '16 at 06:03
  • 1
    Possible duplicate of [getchar not taken in consideration after scanf](http://stackoverflow.com/questions/26828370/getchar-not-taken-in-consideration-after-scanf) – n. m. could be an AI Dec 04 '16 at 06:31

1 Answers1

1

1- move the declaration of struct node *new_node, *current; to outside the do loop (to just before the do), because you want them to keep their values between iterations.

2- a newline character remained in the buffer after the scanf that read the number, because the user had to type return after the number, and the scanf did not consume it. To skip this newline when getting the Y/N answer, get your Y/N answer in this way instead of ch = getchar();:

  scanf(" %c", &ch); // notice the blank before the %c, important to skip the newline that remained in the buffer

3- although not necessary, better avoid using the escape character \ in your question, use "Y/N" instead of "Y\N"

Your code worked perfectly after I made these modifications.

A.S.H
  • 29,101
  • 5
  • 23
  • 50