在数组结构中对数据进行排序

时间:2015-02-16 23:36:08

标签: c arrays sorting structure

我正在编写一个程序,我必须从文件中读取数据,然后按降序对它们进行排序。我在排序部分遇到问题。如何对浮点值进行排序,然后打印排序的结构?这是我的代码。我一直遇到分段错误。我不知道如何解决它。

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

typedef struct importedData {
    char type[100];
    float literAmount;
    int miles;
    char color[20];
}DATA;

void sorting();

int main() {
    int userInput;
    //initialize();
    DATA *data = NULL;
    sorting(data);
    //Do while loop to loop through  menu until exit.
    do {
    //Print statements to put out the output options
        printf("Choose the option you would like to preform \n");
    printf("1.Sort data from the float value & print high to low \n2.Sort data by the float value & print low to high\n3.Sort data by the int value & print high to low\n4.Sort data by the int value & print low to high");
    scanf("%d", &userInput); //Scanner to take in the keyboard input


    } while (userInput != 5);


    return 0;
}

int numberOfLines() {
    FILE *fp = fopen("hw3.data", "r"); //Opens file name and in the read format
    int c = 0; //Count the number of characters
    int count = 0; //Number of lines

    if(fp == NULL) { //If file was not able to be opened program will exit
        printf("Unable to read file. Closing");
        return 0;
    }
    while((c = fgetc(fp)) != EOF) { //Get the character and make sure it isnt the END OF FILE
        if(c == '\n') { //If the charcter is set to \n (New Line) will add one to counter
            count++;
        }
    }
    fclose(fp);
    return count;
}

DATA* initialize(DATA *data) {
    data = malloc(numberOfLines() * sizeof(*data));
    FILE *fp = fopen("hw3.data", "r"); //Opens file name and in the read format
    int counter = 0;
    int totalIterations = numberOfLines();
    while(counter < totalIterations) {
        if(fscanf(fp, "%s %f %d %s\n", data[counter].type, &data[counter].literAmount, &data[counter].miles, data[counter].color) !=4) {
    } 
    printf("data stored is: %s %f %d %s\n", data[counter].type, data[counter].literAmount, data[counter].miles, data[counter].color);
    }
    return (data);
}

void sorting() {
    DATA *data = malloc(numberOfLines() * sizeof(*data));
    FILE *fp = fopen("hw3.data", "r"); //Opens file name and in the read format
    int counter = 0;
    int totalIterations = numberOfLines();
    while(counter < totalIterations) {
        if(fscanf(fp, "%s %f %d %s\n", data[counter].type, &data[counter].literAmount, &data[counter].miles, data[counter].color) ==4) {
    counter++;
    } 
}
    DATA *temp;
    int i, j;
    for(i = 0; i < (numberOfLines() -1); i++) {
        for(j = 0; j < (numberOfLines() -1); j++)  {
            if(data[i].literAmount > data[i+1].literAmount) {
                data[i].literAmount = (*temp).literAmount;
                printf("Temp: %f", (*temp).literAmount);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以拥有这4个比较功能

int compare_literAmount(const void *const lhs, const void *const rhs)
{
    if ((lhs == NULL) || (rhs == NULL))
        return -1;
    return ((int)(((DATA *)lhs)->literAmount)) - ((int)(((DATA *)rhs)->literAmount));
}

int compare_type(const void *const lhs, const void *const rhs)
{
    if ((lhs == NULL) || (rhs == NULL))
        return -1;
    return strcmp(((DATA *)lhs)->type, ((DATA *)rhs)->type);
}

int compare_miles(const void *const lhs, const void *const rhs)
{
    if ((lhs == NULL) || (rhs == NULL))
        return -1;
    return (((DATA *)lhs)->miles) - (((DATA *)rhs)->miles);
}

int compare_color(const void *const lhs, const void *const rhs)
{
    if ((lhs == NULL) || (rhs == NULL))
        return -1;
    return strcmp(((DATA *)lhs)->color, ((DATA *)rhs)->color);
}

然后在阅读完数据后

qsort(data, numberOfItems, sizeof(*data), compare_literAmount);

literAmmount字段排序,依此类推。

您的initialize()函数也非常弱,通过添加一些检查使其更加健壮,并且您可以在while (counter < totalIterations)中导致无限循环,因为您没有检查所有行是否有效numberOfLines(),如果您将fp传递给numberOfLines()而不是在那里打开和关闭文件,那也会更好。

这是对initialize()功能

的修复建议
DATA* initialize(DATA *data) {
    int totalCount = numberOfLines();
    int count      = 0;
    data           = malloc(totalCount * sizeof(*data));
    if (data == NULL)
        return NULL;
    FILE *fp = fopen("hw3.data", "r"); //Opens file name and in the read format
    if (fp == NULL)
    {
        free(data);
        return NULL;
    }
    /* write a safer format string */
    while(fscanf(fp, "%99s%f%d%19s\n", data[count].type, &data[count].literAmount, &data[count].miles, data[count].color) == 4)
        count++;
    qsort(data, count, sizeof(*data), compare_literAmount);
    for (int i = 0 ; i < count ; i++)
        printf("data stored is: %s %f %d %s\n", data[count].type, data[count].literAmount, data[count].miles, data[count].color);

    return (data);
}

注意我做的第一件事就是存储文件中行数的值。因为它会更有效率。