How to access an element in the structure which not the first - Qsort

后端 未结 1 417
轮回少年
轮回少年 2021-01-28 02:53

I am trying to sort the following structure. I am using the qsort to order the books according to date publish in order of the newest first. I completely don\'t understand why t

1条回答
  •  花落未央
    2021-01-28 03:10

    Here is an example of a multikey sort:

    int
    cmp_multikey(const void *a,const void *b)
    {
        const struct book *booka = a;
        const struct book *bookb = b;
        int cmp;
    
        do {
            // sort by year published
            cmp = booka->year_published - bookb->year_published;
            if (cmp)
                break;
    
            // sort by author
            cmp = strcmp(booka->author,bookb->author);
            if (cmp)
                break;
    
            // sort by title
            cmp = strcmp(booka->name,bookb->name);
            if (cmp)
                break;
        } while (0);
    
        return cmp;
    }
    

    Invoke with:

    qsort(books,numberofbooks,sizeof(struct book),cmp_multikey);
    

    Some other tips ...

    [As others have mentioned] Never use gets. Use a switch/case instead of an if/else ladder.

    Try to avoid intermixing scanf and fgets.

    Personally, I prefer to [always] use fgets. Here is a [safe] replacement for gets and a replacment for scanf("%d",&num);:

    int
    getstr(const char *prompt,char *buf,int buflen)
    {
        char *cp;
    
        printf("%s",prompt);
        fflush(stdout);
    
        cp = fgets(buf,buflen,stdin);
        if (cp == NULL) {
            fprintf(stderr,"unexpected EOF\n");
            exit(1);
        }
    
        // find newline
        cp = strchr(buf,'\n');
    
        // ensure we had enough space
        if (cp == NULL) {
            fprintf(stderr,"response too large for buffer\n");
            exit(1);
        }
    
        // strip newline
        *cp = 0;
    }
    
    int
    getnum(const char *prompt)
    {
        char buf[1000];
        int num;
    
        getstr(prompt,buf,sizeof(buf));
    
        num = atoi(buf);
    
        return num;
    }
    

    0 讨论(0)
提交回复
热议问题