如何从 c 中的文本文件为 运行 总计创建多个函数?

How to create multiple functions for running totals from a text file in c?

从文本文件中读取并填充结构数组后,程序应该:

  1. 使用函数输出 关于火车的数据。
  2. 使用函数计算并报告列车中的车厢总数。
  3. 使用函数计算并报告火车所需的总马力。
  4. 使用函数计算并报告总计 火车的长度和
  5. 假设机车产生 1000 马力,计算并报告牵引火车所需的机车数量(四舍五入)。问题是我以前从未这样做过,我什至不知道从哪里开始。使用 strsub() 是强制性的,即使 sscanf() 会使一切变得更容易。

我尝试传递 train[] data 类型并为 运行 总共 train[i].amount 创建一个循环,但显然我做错了什么。

来自traindata.txt

Boxcar    D 44000 55 16 45
Hopper    B 23000 62 18 33
Tanker    G 15000 45 30 12
Autocar   A 30000 37 23 6
Livestock L 56500 50 18 19
Coalcar   C 49300 53 22 100
Flatcar   F 18000 66 15 25

来自train.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX 100
FILE *fpIn;

typedef struct {
    char name[10];
    char type;
    float weight;
    int length;
    int power;
    int amount;
}data;

void strsub(char buf[], char sub[], int start, int end);
int readFile();
int numOfCars(data *, int);
int horsePower(data *, int);
int trainLen(data *, int);
int engNeed(int);

// Substring extractor function from book
void strsub(char buf[], char sub[], int start, int end){
    int i, j;

    for (j = 0, i = start; i <= end ; i++, j++){
        sub[j] = buf[i];
    }
    sub[j] = '[=12=]';
}

// Prints out file
void outFile(data* train) {
    printf(" Name: %s ", train->name);
    printf(" Type: %c ", train->type);
    printf(" Weight: %.2f ", train->weight);
    printf(" Length: %d ", train->length);
    printf(" Horsepower: %d ", train->power);
    printf(" Number in Train: %d ", train->amount);

}

// Reads file
int readFile(){
    int count = 0;
    data train[MAX];

    // Opens file
    if(!(fpIn = fopen("traindata.txt", "r"))){
        printf("Error. File can not be opened. \n");
    }

    // Reads each line of text in file
    while (!feof(fpIn)){
        char buf[MAX+2];
        char weightbuf[7];
        char lengthbuf[4];
        char powerbuf[4];
        char amountbuf[6];

        fgets(buf, MAX, fpIn);
        strsub(buf, train[count].name, 0, 8);
        train[count].type = buf[10];
        strsub(buf, weightbuf, 11, 16);
        strsub(buf, lengthbuf, 17, 19);
        strsub(buf, powerbuf, 20, 22);
        strsub(buf, amountbuf, 23, 26);
        train[count].weight = atof(weightbuf);
        train[count].length = atoi(lengthbuf);
        train[count].amount = atoi(amountbuf);
        train[count].power = atoi(powerbuf);
        ++count;

        // where to make those additions
    }

    for (int i = 0; i < count; ++i){
        data* trains = &train[i];
        outFile(trains);
    }
}

int numOfCars(data train[],int len){
    int i,total_cars=0;

    for(i=0;i<len;++i){
        total_cars+=train[i].amount;
    }
    return total_cars;
}

int main(int argc, char *argv[]) {
    data train[20];
    printf("This table shows the current Train Cars\n");
    printf("---------------------------------------\n\n");

    int len = readFile();
    printf("\n\nThere are %d Cars in the train.\n", numOfCars(train,len));

    return 0;
}

这table显示当前的火车车厢

Name: Boxcar     Type: D  Weight: 44000.00  Length: 55  Horsepower: 16  Number in Train: 45 
Name: Hopper     Type: B  Weight: 23000.00  Length: 62  Horsepower: 18  Number in Train: 33 
Name: Tanker     Type: G  Weight: 15000.00  Length: 45  Horsepower: 30  Number in Train: 12  
Name: Autocar    Type: A  Weight: 30000.00  Length: 37  Horsepower: 23  Number in Train: 6  
Name: Livestock  Type: L  Weight: 56500.00  Length: 50  Horsepower: 18  Number in Train: 19  
Name: Coalcar    Type: C  Weight: 49300.00  Length: 53  Horsepower: 22  Number in Train: 100  
Name: Flatcar    Type: F  Weight: 18000.00  Length: 66  Horsepower: 15  Number in Train: 25 

There are 240 Cars in the train.
The total length of the train is 13183
Total horsepower needed to pull train is 4729
The number of engines need to pull the train is 5

大问题在这里:

int readFile(){
    int count = 0;
    data train[MAX];  // Local value used for storing data read from the file

当您从文件读取数据并将数据存储到 local 变量时,这些数据将在函数 returns 时丢失。换句话说 - main 函数中的 train 变量不会保存从文件中读取的数据。

要解决这个问题,您需要将 train 变量从 main 传递给函数。喜欢:

int readFile(data train[]){
    int count = 0;
    // delete this line !! data train[MAX];
    ...

main 中这样称呼它:

int len = readFile(train);

请注意,传递数组可以容纳的最大元素数也是一个好主意。所以考虑:

int readFile(data train[], int max){
    int count = 0;

并这样称呼它:

data train[20];
int len = readFile(train, sizeof(train) / sizeof(data));

或者:

data train[MAX];
int len = readFile(train, MAX);

感谢@4386427,这是最后一段代码。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX 100
FILE *fpIn;

typedef struct {
    char name[10];
    char type;
    float weight;
    int length;
    int power;
    int amount;
}data;

void strsub(char buf[], char sub[], int start, int end);
int readFile(data train[]);
void outFile(data train[]);
int numOfCars(data train[], int num);
int horsePower(data train[], int num);
int trainLen(data train[], int num);

// Substring extractor function from book
void strsub(char buf[], char sub[], int start, int end){
    int i, j;

    for (j = 0, i = start; i <= end ; i++, j++){
        sub[j] = buf[i];
    }
    sub[j] = '[=10=]';
}

// Prints out file
void outFile(data train[]) {
    printf(" Name: %s ", train->name);
    printf(" Type: %c ", train->type);
    printf(" Weight: %.2f ", train->weight);
    printf(" Length: %d ", train->length);
    printf(" Horsepower: %d ", train->power);
    printf(" Number in Train: %d ", train->amount);

}

// Reads file
int readFile(data train[]){
    int count = 0;

    // Opens file
    if(!(fpIn = fopen("traindata.txt", "r"))){
        printf("Error. File can not be opened. \n");
    }

    // Reads each line of text in file
    while (!feof(fpIn)){
        char buf[MAX+2];
        char weightbuf[7];
        char lengthbuf[4];
        char powerbuf[4];
        char amountbuf[6];

        fgets(buf, MAX, fpIn);
        strsub(buf, train[count].name, 0, 8);
        train[count].type = buf[10];
        strsub(buf, weightbuf, 11, 16);
        strsub(buf, lengthbuf, 17, 19);
        strsub(buf, powerbuf, 20, 22);
        strsub(buf, amountbuf, 23, 26);
        train[count].weight = atof(weightbuf);
        train[count].length = atoi(lengthbuf);
        train[count].amount = atoi(amountbuf);
        train[count].power  = atoi(powerbuf);
        ++count;
    }

    for (int i = 0; i < count; ++i){
        data* trains = &train[i];
        outFile(trains);
    }

    numOfCars(train, count);
    trainLen(train, count);
    horsePower(train, count);

    return 0;
}

int numOfCars(data train[], int num){
    int i, totalCars = 0;

    for(i = 0; i < num; i++)
        totalCars += train[i].amount;

    printf("\n\nThere are %d Cars in the Train.", totalCars);
    return totalCars;
}

int trainLen(data train[], int num){
    int i, totalLen = 0;

    for(i = 0; i < num; i++)
        totalLen += (train[i].length * train[i].amount);

    printf("\nThe total length of the train is: %d", totalLen);
    return totalLen;
}

int horsePower(data train[], int num){
    int i, totalHp = 0;

    for (i = 0; i < num; i++)
        totalHp += (train[i].amount * train[i].power);

    printf("\nThe total horsepower need for this train is: %d", totalHp);

    int engNeed = totalHp/1000;
    if (totalHp % 1000 != 0)
        engNeed = engNeed+1;

    printf("\n%d number of engines are needed to pull the train.", engNeed);

    return totalHp, engNeed;
}

int main() {
    data train[MAX];

    printf("This table shows the current Train Cars\n");
    printf("---------------------------------------\n\n");

    readFile(train);

    return 0;
}