如何在C编程中从文本文件读取数据和数据到数组结构? [英] How to read and data from text file to array structure in c programming?

查看:71
本文介绍了如何在C编程中从文本文件读取数据和数据到数组结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序应使用函数从每一行读取数据,以获取有关汽车名称,货物类型,重量(满),长度,拉动该汽车类型所需的马力以及该类型汽车数量的信息。从文件中读取数据然后将其显示在控制台中时,数据必须存储在结构数组中。必须使用 strsub()函数。

By using a function, the program should read the data from each line as information about a car’s name, cargo type, weight (full), length, required horsepower to pull that car type, and number of cars of that type. The data must be stored in an array of structures as it is being read from the file then displayed in console. The strsub() function must be used.

不幸的是,文本文件中的数据没有打印到安慰。我认为问题可能出在我对指针的使用上,但是我已经阅读了超过五章。

Unfortunately the data from the text file isn't printing to the console. I think the problem may lie in my use of pointers, but I've read the chapter on it more than five times now. And if it does print, only gibberish prints.

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

void strsub(char buf[], char sub[], int start, int end);
void readFile();

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

// 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] = '\0';
}

// Prints out file
void outFile(data* train) {

    printf(" Name: %s ", train->name);
    printf(" Type: %s ", 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
void 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[5];
        char lengthbuf[3];
        char powerbuf[2];
        char amountbuf[3];

        fgets(buf, MAX, fpIn);
        strsub(buf, train[count].name, 0, 8);
        strsub(buf, train[count].type, 10, 10);
        strsub(buf, weightbuf, 12, 16);
        strsub(buf, lengthbuf, 18, 20);
        strsub(buf, powerbuf, 22, 23);
        strsub(buf, amountbuf, 25, 27);
        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* train = &train[i];
        outFile(train);
    }
}

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

    return 0;
}



Expected results:
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

Current Display:
This table shows the current Train Cars

 Name: ����  Type:   Weight: 0.00  Length: 20  Horsepower: 1696  Number in Train: -2112880507

Error?:
data* train = &train[i];
  - Local variable "train" might not have been initialized


推荐答案


  1. 数组大小错误。



    char type[1];
    printf(" Type: %s ", train->type);

类型无法容纳 \0 字符,当您将其传递给 printf 或超出范围时,您将获得不确定的行为。

Type cannot hold \0 character as you pass it to the printf or access out of bound, you have undefined behavior.

解决方案:

char type;
train[count].type = buf[10]; //Do not call substr function.
printf(" Type: %c ", train->type);








  1. 范围问题。



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

此处火车为数组比 train 作为指针具有更高的优先级,因此您在不知不觉中将 train 作为数组传递给 outFile 函数。

Here train as array has higher preference over train as pointer, thus you are unknowingly passing train as array to outFile function.

解决方案:

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




建议:使用 sscanf 函数。

这篇关于如何在C编程中从文本文件读取数据和数据到数组结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆