在单链表中的第一个循环后输入数据时跳过 gets() 函数

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

我正在尝试创建一个程序,我们可以在其中使用单链表在 C 中输入 Mess(Canteen) 详细信息,例如食物名称、份数等。 这里的食物名称是字符串形式,在输入食物名称的第一个循环之后,程序不接受任何输入,而是直接跳到 insertinto() 函数中的“输入份量”。

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

我还没有对此进行测试,但是:问题很可能是,scanf 读取输入直到到达 newlint ,但将换行保留在输入缓冲区中

gets 查看缓冲区并读取直到到达换行符,换行符尚未被 scanf 删除,因此这是它第二次看到的第一件事。

简单修复:在 scanf:

之后添加 getchar();
scanf("%d",&ch);
getchar();

另外:

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.