在另一个文件中输出

时间:2016-04-04 03:08:33

标签: c file io

    int i, largest = 0, temp, temp2, temp3;






            temp1 = products[n-1].name;

            strcpy(products[n-1].name,products[largest].name);

            strcpy(products[largest].name, temp1);

这些是问题的关键点,问题现在已得到修复,感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

第一个问题是temptemp2temp3int,但您要为其分配double个值,然后重新 - 将这些值分配回double个变量。你应该制作这些double

您可能需要考虑使用qsort()对这些对象进行排序。

#include <stdlib.h> // for qsort

int compare_products(const void *p1, const void *p2)
{
    const struct product *product1 = p1;
    const struct product *product2 = p2;

    // swap product1 and product2 around to reverse sort order
    return (int)(product1->sale_volume - product2->sale_volume);
}

int main()
{
     // ...

     qsort(products, line_amount, sizeof(struct product), compare_products);

     for(i = 0; i < line_amount; i++){
         fprintf(pFile, "%s \t  %lf \t %lf \t %lf\n", products[i].name, products[i].unit_price, products[i].tot_pounds_sold, products[i].sale_volume);
     }

     // ...    
}

由于您必须使用selection_sort函数,因为可以分配struct个对象,所以可以使它更简单。

void selection_sort(struct product products[], int n)
{
    int i, largest = 0;

    if (n == 1) {
        return;
    }

    for (i = 0; i < n; i++) {
        if (products[i].sale_volume > products[largest].sale_volume) {
            largest = i;
        }
    }

    struct product temp = products[n - 1];
    products[n - 1] = products[largest];
    products[largest] = temp;

    selection_sort(products, n - 1);
}