Frage

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;
    }
}
War es hilfreich?

Lösung

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?

Andere Tipps

It's exactly what @codaddict said. You need to clean the buffer.

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

You can read this links that explains it very well:

  1. c-faq
  2. And this mdsn if you are on windows.

One more thing, try to always use fgets -instead of gets-, as it is impossible to prevent buffer overflows if you are using gets.

You could read the section "Use of safe libraries" at this link

you should also add a line like

 current->next = 0;

after

 current=current->next;

to ensure that the last element's next is not dangling.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top