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不允许输入数据带空格

    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?