我正在为一个班级分配作业,但我无法将文件输入/输出和结构一起应用。我有这段代码可以从一个文件中读取不同的汽车并将它们的信息复制到一个结构数组中。
#include <stdio.h>
#define MAX_LEN 1000
#define NAME_LEN 30
struct car{
char make[NAME_LEN + 1];
char model[NAME_LEN + 1];
int year;
int cmpg;
int hmpg;
int avgmpg;
};
.
.
.
int main()
{
int i;
struct car cars[MAX_LEN];
FILE* pFile;
pFile = fopen("cars.txt", "r");
.
.
.
.
for(i = 0; i < MAX_LEN; i++)
{
while(!feof(pFile) && !ferror(pFile))
{
fscanf(pFile, "%s%s%d%d%d ", cars[i].make, cars[i].model, &cars[i].year, &cars[i].cmpg, &cars[i].hmpg);
cars[i].avgmpg = (cars[i].cmpg + cars[i].hmpg) / 2;
}
}
selection_sort(cars, MAX_LEN);
FILE* outFile;
outFile = fopen("sorted_cars.txt", "w");
fprintf(outFile, "Make Model year city mpg highway mpg average mpg\n");
for(i = 0; i < MAX_LEN; i++);
{
fprintf(outFile, "%s %s %d %-2d %-10d %-12d\n", cars[i].make, cars[i].model, cars[i].year, cars[i].cmpg, cars[i].hmpg, cars[i].avgmpg);
printf("%s %s %d %d %d %d\n", cars[i].make, cars[i].model, cars[i].year, cars[i].cmpg, cars[i].hmpg, cars[i].avgmpg);
}
fclose(pFile);
fclose(outFile);
return 0;
}
这是 .txt 文件的样子:
Mercury Sable 2009 18 28
Jeep Wrangler 2016 17 21
Honda Civic 2015 31 41
Toyota Corolla 2015 30 42
Toyota Prius 2010 51 48
Ford Escape 2013 23 33
Ford Fusion 2013 25 37
Acura MDX 2014 20 28
Lexus RX 2013 32 28
我在我的代码中插入了一个打印函数,这样我就可以查看汽车是否正确读取,但是当我运行程序时,这是输出:
▒▒▒8 0 0 1465899048 32767
我完全不知道为什么会这样。有人可以帮忙吗?