繁体   English   中英

用指针对C中的结构数组进行排序

[英]Sorting an array of structs in C with pointers

我的CIS班有一个编码作业。 任务是编写一个程序,它将创建一个结构数组,最多可容纳10条狗的信息。 在程序的最后,您应该按照名称或大小对狗的数组进行排序。 但是我无法编码狗数组的排序。

我想知道如何对狗的数组进行排序以供以后在main函数中使用。

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

struct Dog{
    char name[20];
    int weight;
    int age;
    int ageDogYears;
    char size[7];
};

typedef struct Dog DG;

void calc(DG[], int);
void sort(DG[], int);
void display();

int main(){
    DG dArray[10];
    int x = 0;
    char str[80], *i;

    FILE *inFile;

    inFile = fopen("dogfile.txt", "r");
    if (inFile == NULL){
        printf("Error opening file");
        exit(1);
    }

    while(fgets(str, 80,inFile) != NULL){
        i = strtok(str, ", ");
        strcpy(dArray[x].name, i);
        puts(dArray[x].name);

        i = strtok(NULL, ", ");
        dArray[x].weight = atoi(i);
        printf("%d\n", dArray[x].weight);

        i = strtok(NULL, ", ");
        dArray[x].age = atoi(i);
        printf("%d\n", dArray[x].age);

        x++;
    }

    calc(dArray, x);

    sort(dArray, x);

    return 0;
}

void calc(DG dog[], int numDogs){
    int y, i, total;
    for(i = 0; i < numDogs; ++i){
        if(dog[i].weight <= 20){
            //sets the dog size to small
            strcpy(dog[i].size, "Small");

            for(y = 0; y < dog[i].age; ++y){
                if(y == 0)
                    total += 15;
                else if(y == 1)
                    total += 8;
                else if(y == 2)
                    total += 5;
                else
                    total += 4;
            }
        }
        else if(dog[i].weight <= 50){
            //sets the dog size to medium
            strcpy(dog[i].size, "Medium");

            for(y = 0; y < dog[i].age; ++y){
                if(y == 0)
                    total += 14;
                else if(y == 1)
                    total += 9;
                else if(y == 2)
                    total += 7;
                else
                    total += 5;
            }
        }
        else{
            //sets the dog size to Large
            strcpy(dog[i].size, "Large");

            for(y = 0; y < dog[i].age; ++y){
                if(y == 0)
                    total += 12;
                else if(y == 1)
                    total += 9;
                else if(y == 2)
                    total += 8;
                else
                    total += 7;
            }
        }

        dog[i].ageDogYears = total;
        total = 0;
    }
}

void sort(DG dog[], int numDogs){
    int sortType, i, y, temp;

    printf("\n wlould you like to sort by name(N) or size(S): ");
    scanf("%c", &sortType);

    switch(sortType){
        case 'N': case 'n':
            for(i = 0; i < numDogs; ++i){
                for(y = 0; y < (numDogs); ++y){
                    if(dog[y].weight > dog[y+1].weight){
                        temp = dog[y];
                        dog[y] = dog[y + 1];
                        dog[y + 1] = temp;
                    }
                }
            }
            break;
        default:
            if((sortType != 's') && (sortType != 'S'))
                printf("\n invalid input! Setting sort type to size.");
        //sorting of dog names
    }
}

样本输入

Fluffy,23,6 Fido,65,7 Pepper,44,5 Bowser,75,10 Victor,10,2 Sassy,51,1

任何帮助将不胜感激! 谢谢。

在我看来,您的错误存在(尽管我将在下面进行其他评论),尽管将%c指定为格式描述符以将指针传递给int进行匹配。 您必须传递一个指向char的指针以使scanf(3)选择将字符放入的适当位置。 您可能没有得到正确的字符或根本没有字符(这导致程序中的未定义行为)

其他一些问题是,当要求按名称(在n输入字符上)进行排序时,您正在使用结构的weight字段以及类似的其他错误。 这包括在内部循环限制条件中使用y < (numDogs) (必须为y < (numDogs - 1) ,或者将y -esim与y+1 -esim元素进行比较(超出数组范围) )

另外,由于两个排序选项都使用相同的算法 ,因此我应该在内部循环(进行比较)中包含switch语句,否则将迫使您两次复制相同的排序代码(对于整个排序算法),如:

for(i = 0; i < numDogs; ++i){
    for(y = 0; y < (numDogs - 1); ++y){
        int sortResultGreater;
        switch (sortType) {
        case 'n': case 'N':
             sortResultGreater = strcmp(dog[y].name, dog[y+1].name) > 0; 
             break;
        default: {  /* this should be done as soon as you know the sorting type, not here inside the loop, of course */
             static int not_already_printed = 1;
             if (not_already_printed) {
                 printf("Error, sortType must be [nNsS], defaulting to n\n");
                 not_already_printed = 0; /* so we don't get here again */
             }
        } /* scope of not_already_printed finishes here */
        /* no break used here to fallback to the next case */
        case 's': case 'S':
             sortResultGreater = dog[y].weight > dog[y+1].weight; 
             break;
        } /* switch */
        if(sortResultGreater){
            temp = dog[y];
            dog[y] = dog[y + 1];
            dog[y + 1] = temp;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM