Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gets() does not read user input

Tags:

c

gets

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;
    }
}
like image 681
Bijoy Avatar asked Jan 18 '23 05:01

Bijoy


1 Answers

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?

like image 165
codaddict Avatar answered Jan 25 '23 16:01

codaddict