【发布时间】:2016-11-28 00:42:10
【问题描述】:
我正在尝试通过 fscanf 读取文件 test.txt 并将其存储在结构数组中。这是我尝试过的。这里的问题是fscanf 没有按预期工作。读取文件后,我也尝试在屏幕上打印,但它不起作用。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Item {
double value;
int unit;
char name[50];
};
int load(struct Item* item, FILE* data);
void display(struct Item item, int variableA);
int main()
{
struct Item I;
int i;
char ck;
ck = fopen("test.txt", "r");
if (ck)
{
for (i = 0; i < 3; i++)
{
load(&I, ck);
display(I, 0); //DISPLAY FUNCTION THAT READS test.txt and DISPLAYS
}
fclose(ck);
}
return 0;
}
int load(struct Item* item, FILE* data)
{
fscanf(data, "%d,%.2lf,%s\n", &(*item).unit,&(*item).value,&(*item).name);
return 0;
}
void display(struct Item item, int variableA)
{
printf("|%3d |%12.2lf| %20s |***\n", item.unit, item.value, item.name);
return;
}
这是我在 test.txt 文件中的内容:
205,11.20,John Snow
336,23.40,Winter is coming
220,34.20,You know nothing
错误: 程序编译时出现一些警告,但执行代码时出现分段错误。
知道为什么吗?
输出预期:应该从 test.txt 文件中读取 OUTPUT 并显示在屏幕上。
【问题讨论】:
-
可能是因为“John”不正确;那是“乔恩”斯诺……
-
@ringø 哈哈 :D :D :D
-
您必须调试程序以查看错误发生的位置(读取或显示),并查看您是否得到了您认为应该得到的结果。
-
好吧,一方面,
fopen不返回char,它返回FILE*。不要忽视警告。他们在那里告诉你有什么问题。所以修复他们。