结构体2022

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

typedef struct vegetables {
    // 蔬菜名称
    char name[20];
    // 销售量
    int saleVolume;
    // 销售价格
    int salePrice;
}Vegetables;

char basePath[20] = "E:\\clion-space\\";

int readFileLine(FILE *fp) {
    int len = 0;
    char ch;
    while ((ch = fgetc(fp)) != EOF) {
        if (ch == '\n') {
            len++;
        }
    }
    return len;
}

int totalStatistic() {
    // 文件名
    char filename[20] = "file1.txt";
    int total = 0;
    for (int i = 1; i <= 7; ++i) {
        // 文件路径
        char filePath[40] = {};
        filename[4] = (char)(i + '0');
        strcat(filePath, basePath);
        strcat(filePath, filename);
        FILE *fp = fopen(filePath, "r");
        if (NULL == fp) {
            printf("打开文件%d失败", i);
            continue;
        }
        total += readFileLine(fp);
        fclose(fp);
    }
    return total;
}

int readData(FILE *fp, int index, Vegetables* arr) {
    while (!feof(fp)) {
        fscanf(fp, "%s%d%d", arr[index].name, &arr[index].saleVolume, &arr[index].salePrice);
        if (arr[index].salePrice != 0 && arr[index].saleVolume != 0) {
            index++;
        }
    }
    return index;
}

Vegetables* readDataFromFile(int len) {
    Vegetables* arr = (Vegetables*) malloc(sizeof(Vegetables) * len);
    int index = 0;
    char filename[20] = "file1.txt";
    for (int i = 1; i <= 7; ++i) {
        // 文件路径
        char filePath[40] = {};
        filename[4] = (char)(i + '0');
        strcat(filePath, basePath);
        strcat(filePath, filename);
        FILE *fp = fopen(filePath, "r");
        if (NULL == fp) {
            printf("打开文件%d失败", i);
            continue;
        }
        // 从文件中读取数据
        index = readData(fp, index, arr);
        fclose(fp);
    }
    return arr;
}


int main() {
    // 统计总数
    int total = totalStatistic();
    // 从文件中读取数据到arr中
    Vegetables* arr = readDataFromFile(total);
    for (int i = 0; i < total; ++i) {
        printf("%d ----- %s %d %d\n",i,  arr[i].name, arr[i].saleVolume, arr[i].salePrice);
    }
    // 对arr进行排序
    bubbleSort(arr, total);
    char *name = arr[0].name;
    int totalPrice = arr[0].saleVolume * arr[0].salePrice;
    for (int i = 1; i < total; ++i) {
        if (strcmp(name, arr[i].name) == 0) {
            totalPrice += arr[i].saleVolume * arr[i].salePrice;
        } else{
            printf("%s的总销售额为: %d\n", name, totalPrice);
            name = arr[i].name;
            totalPrice = arr[i].saleVolume * arr[i].salePrice;
        }
    }
    printf("%s的总销售额为%d\n", name, totalPrice);
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值