Descartes_lyh 2020-06-30 14:00 采纳率: 0%
浏览 78

函数两次运行情况不同。

我想要在函数create中多次执行输出结构体指针的函数 input,来建立一个动态链表。第一次input函数运行正常,但是在第二次运行input时,第一个需要运行的gets()函数被跳过去了。不清楚这是为什么。

struct goods *create(int *pn)
{
    struct goods *p1,*p2,*head;
    int i=0;
    p1=input();
    p2=p1;
    while(p1->num!=0){
        i++;
        if(i==1) head=p1;
        else p2->next=p1;
        p2=p1;
        p1=input();
    }
    p2->next=NULL;
    *pn=i;
    return(head);
};
struct goods *input(void)
{
    char assist[25];
    struct goods *p;
    p=(struct goods *)malloc(LEN);
    printf("input the number of a sort of goods\n");
    gets(assist); p->num=atol(assist);
    printf("input the name of the sort of goods\n");
    scanf("%[^\n]%*c",p->name);
    printf("input the mod of the sort of goods\n");
    gets(assist); p->mod=atoi(assist);
    printf("input the price of the sort of goods\n");
    gets(assist); p->price=atof(assist);
    printf("input the producer of the sort of goods\n");
    scanf("%s",p->producer);
    return(p);
};
  • 写回答

1条回答 默认 最新

  • _花花 2020-06-30 14:51
    关注

    scanf遇空格和回车结束输入,gtes遇回车结束输入
    如果第一次运行的最后一个输入有遗留回车,在第二次运行时被gets捕获到,gets会直接处理完成输入,造成该代码未执行跳过的错觉
    建议严格控制输入或者全部使用scanf不允许输入数据带空格

    评论

报告相同问题?

悬赏问题

  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的