Gets () does not read user input

I am new to the linked list, now I have few problems with the population of nodes.

Here I could populate the first node of the linked list, but the gets() function does not seem to pause execution to populate the next node.

The output is similar:

 Var name : var Do you want to continue ?y Var name : Do you want to continue ? // Here I cannot input second data 

Here is my code:

 struct data { char name[50]; struct data* next; }; struct data* head=NULL; struct data* current=NULL; void CreateConfig() { head = malloc(sizeof(struct data)); head->next=NULL; current = head; char ch; while(1) { printf("Var name : "); gets(current->name); //Here is the problem, printf("Do you want to continue ?"); ch=getchar(); if(ch=='n') { current->next=NULL; break; } current->next= malloc(sizeof(struct data)); current=current->next; } } 
+4
source share
3 answers

This is because:

 ch=getchar(); 

read either y or n from the input and assign ch , but there is a new line in the input buffer that gets at the next iteration.

To fix this, you need to use a new line after y/n that the user enters. To do this, you can add another getchar() call as:

 ch=getchar(); // read user input getchar(); // consume newline 

You should also use the fgets function instead of gets . Why?

+7
source

This is exactly what @codaddict said. You need to clear the buffer.

 void fflushstdin( void ) { int c; while( (c = fgetc( stdin )) != EOF && c != '\n' ); } 

You can read these links that explain very well:

One more thing, try to always use fgets - instead of get-, since it is impossible to prevent buffer overflows if you use get.

You can read the "Using Safe Libraries" section in this link.

+2
source

you should also add a line like

  current->next = 0; 

after

  current=current->next; 

so that the last element does not hang.

0
source

Source: https://habr.com/ru/post/1382350/


All Articles