为什么我运行C程序时什么也没发生?

时间:2017-02-27 13:18:52

标签: c list

我写了以下代码:

#include <stdio.h>
#include <stdlib.h>


typedef struct 
{
    int month;
    int day;
    int hour;  
    int minutes;
    }primaries_date;

typedef struct 
{
    int all_members;
    char *country;
    primaries_date date;
}usa_primaries;

typedef struct node *ptr;

typedef struct node
{
    usa_primaries up;
    ptr next;
}Node;



void add(ptr *hptr, int members, char *con, int month, int day, int     hour, int minutes)
{
    ptr p = NULL;
    ptr q = NULL;
    ptr t;
    t = malloc(sizeof(Node));
    if(!t)
    {
         printf("Cannot build list");
         exit(0);
    }

    t->up.all_members = members;
    t->up.country = con;
    t->up.date.month = month;
    t->up.date.day = day;
    t->up.date.hour = hour;

   while( (p) )
   {
     if( p->up.date.month >= month || p->up.date.day >= day ||     p->up.date.hour >= hour || p->up.date.minutes >= minutes )
       { 
            q = p;
            p = p->next;
       }
   }

   if(p == *hptr)
   {
        *hptr  = t; /*Resetting head. Assigning to the head t*/
         t->next = p; 
   }
   else
   {
       q->next = t;
       t->next = p;
   }





}

void remove_dates(ptr *hptr, primaries_date date1 , primaries_date date2)
{
    ptr p1 = *hptr;
    ptr p2 = p1;
    while( (p1) && !( (p1->up.date.month == date1.month) &&     (p1->up.date.day == date1.day) && (p1->up.date.hour == date1.hour) && 
           (p1->up.date.minutes==date1.minutes ) ) )
              p1 = p1->next;


          p2 = p1;

    while( (p2) && !( (p2->up.date.month == date2.month) &&    (p2->up.date.day == date2.day) && (p2->up.date.hour == date2.hour) && 
(p2->up.date.minutes==date2.minutes ) ) )
       p1 = p1->next;

    p1->next = p2;

}












void printlist(ptr h)
{
    while(h)
    {
        printf("\n");
   printf("%d %d %d %d %d %s\n", h->up.date.day, h->up.date.month,     h->up.date.hour, h->up.date.minutes, h->up.all_members, h->up.country);
        h = h->next;
    }
}


void freelist(ptr *hptr)
{    
    ptr p;
    while(*hptr)
    {
        p = *hptr;
        *hptr = (*hptr)->next;
        free(p);
   }


}





int main()
{
    ptr h = NULL;
    int month, day, hour, minutes; 
    int all_members; /*Declaration of all_members*/
    char country[256]; 
   char member;

   while( scanf("%d %d %d %d %c  %s",&day,&month,&hour,&minutes,&member,country) == 1)
   {
       if(member == 'Y')
           all_members = 1;
      else
        all_members = 0;
       add(&h,all_members,country,month,day,hour,minutes);
        printlist(h);
   }


freelist(&h);


    return 0;
}

没有编译错误。但是,当我运行程序时,什么也没发生。 我认为它可能是由于scanf函数引起的,因为scanf存储了&#39; \ n&#39;扫描字符时的字符(输入键),但我不确定。

为什么在运行程序时没有发生任何事情,如何让它正常运行?

提前致谢!

1 个答案:

答案 0 :(得分:3)

scanf返回它成功解析的转换说明符数。假设它是正确的,那么它将在您的输入上返回大于1的值。您应该将它与实际要求它阅读的项目数进行比较。

所以不言而喻,如果你使用scanf来解析输入,不要一次读取太多,或者你通过与魔术数字的比较乱丢你的代码