I have written a code for Linked List:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student{
char name[256];
int id;
struct student *next;
};
struct student *start;
struct student *last;
void enter(void);
void add( struct student *i,struct student **last);
void display(struct student *first);
int main(int argc, char *argv[])
{
start=last=NULL;
enter();
enter();
enter();
display(start);
system("PAUSE");
return 0;
}
void add( struct student *i,struct student **last)
{
if (!*last){ *last=i; start=i;}
else {(*last)->next=i;*last=i;}
i->next=NULL;
}
void enter(void)
{
struct student *info;
info=(struct student *)malloc(sizeof(struct student));
printf("Enter the name of the student:\n");
fgets(info->name,255,stdin);
fflush(stdin);
// gets(info->name);
printf("Enter the student id:\n");
scanf("%d%",&info->id);
add(info,&last);
}
void display(struct student *first)
{
while(first)
{
printf("\n\n\n\nName: %s\n",first->name);
printf("Id: %d\n", first->id);
first=first->next;
}
}
It does create a linked list but when i try to input the values: it shows

For first element it takes the name correctly for id i need to manually enter \n after the id digit (otherwise it does not come out of the scanf mode) and 2nd element onwards it does not prompt to take the name and it skips “Enter name” and asks for id where again I need to manually enter \n. While showing the linked list elements , it does show first name but 2nd name onwards shows \n. I have already used fflush(stdin). Could you please let me know why such behavior? I have attached the o/p pic.
Thanks
If I had a nickel…
Anyway, there are a number of problems here:
1) Don’t
fflush(stdin), that’s undefined behavior2) It’s never a good idea to mix
scanfs andfgetss, it just makes things confusing.3) You have an extra
%in your scanf:For completeness…
Why you’re having problems right now:
fgets()takes a string and includes the newline, so when you’re asking for a name you’re getting “name\n”scanf()takes the number and leaves the newline. So when you ask for an ID, you’ll get the digit typed, but the newline character'\n'is still sitting instdin.Next time that your
fgets()runs it will automatically take that as the input for the second name. Seeming to “skip over” the request for input.EDIT
If the reason you were using
fgets()was to read a string with spaces in it (like"first_name last_name") that can be acomplished withscanf()as well using the Negated scanset option: