I am new to linked list, now I have little problems in population of nodes.
Here I could populate first node of linked list but the gets()
function doesn't seems to pause the execution to fill the next node.
Output is like:
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;
}
}
This happens because:
ch=getchar();
read either y
or n
from the input and assigns to ch
but there a newline in the input buffer which gets read by the gets
in the next iteration.
To fix that you need to consume the newline following the y/n
the user enters. To do that you can add another call to getchar()
as:
ch=getchar(); // read user input
getchar(); // consume newline
Also the function fgets
should be used in place of gets
. Why?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With