Search code examples
cstringlinked-liststructuregets

gets() function gets skipped while entering data after first loop in singly linked list


I am trying to create a program where we can input Mess(Canteen) details in C using singly linked list, such as Food name, no of servings etc. Here the food name is in string and after the first loop while entering food name the program doesn't take any input but straight out skips to "Enter Servings" in insertinto() function.

struct node{

    char food[100];
    int serv;
    int weight;
    int credits;
    struct node *next;
}*head[6],*temp[6],*newnode[6]; //for 7 days a week

int insertinto(){
    int d=0; //just for example
    //linked list insertion
    int ch=0;
    while(ch==0){
        head[d]=0;
        newnode[d]=(struct node *)malloc(sizeof(struct node));
    //newnodex->datax=xx;

        printf("Enter food: ");
        gets(newnode[d]->food); //error occurs here on second iteration of while loop
        printf("Enter Servings: ");
        scanf("%d",&newnode[d]->serv);
        printf("Enter wt per Servings in gram: ");
        scanf("%d",&newnode[d]->weight);
        printf("Enter Credits required for the food to be consumed: ");
        scanf("%d",&newnode[d]->credits);
        newnode[d]->next=0;

        if(head[d]==0){
            head[d]=temp[d]=newnode[d];
        }
        else{
            temp[d]->next=newnode[d];
            temp[d]=newnode[d];
        }

        printf("Do you want to enter the data of more Food?(0=Yes): ");
        scanf("%d",&ch);
    }


};

int main()
{
    insertinto();
}




OUTPUT


Solution

  • I haven't tested this, but: The problem is likely, that scanf reads input until it reaches newlint but keeps the newline in input buffer.

    The gets looks into buffer and reads until it reaches newline, which have not been removed by scanf, so it is the first thing it sees second time around.

    Simple fix: add getchar(); after the scanf:

    scanf("%d",&ch);
    getchar();
    

    ALSO:

    Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.