程序应使用函数从每一行读取数据,以获取有关汽车名称,货物类型,重量(满),长度,拉动该汽车类型所需的马力以及该类型汽车数量的信息。从文件读取数据然后将其显示在控制台中时,数据必须存储在结构数组中。必须使用strsub()
函数。
不幸的是,文本文件中的数据没有打印到控制台。我认为问题可能出在我对指针的使用上,但是我已经阅读了超过五章。如果可以打印,则只能打印乱码。
#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
答案 0 :(得分:3)
char type[1];
printf(" Type: %s ", train->type);
Type
不能将\0
字符传递给printf
或超出范围访问,则具有不确定的行为。
解决方案:
char type;
train[count].type = buf[10]; //Do not call substr function.
printf(" Type: %c ", train->type);
for (int i = 0; i < count; ++i){
data* train = &train[i];
outFile(train);
}
这里train
作为数组比train
作为指针具有更高的优先级,因此您在不知不觉中将train
作为数组传递给outFile
函数。
解决方案:
for (int i = 0; i < count; ++i){
data* pTrain = &train[i];
outFile(pTrain );
}
建议:使用
sscanf
功能。