gpt4 book ai didi

c - C编程:读取文件并存储在struct数组中

转载 作者:行者123 更新时间:2023-12-02 08:14:59 27 4
gpt4 key购买 nike

我正在尝试通过fscanf读取文件test.txt并将其存储在struct数组中。这就是我尝试过的。这里的问题是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,并应将其显示在屏幕上。

最佳答案

程序中的多个问题:

1。

char ck;
ck = fopen("test.txt", "r");


fopen返回 FILE*,而不是 char,使用

FILE* ck = fopen(...);


2。

fscanf(data, "%d,%.2lf,%s\n", &(*item).unit,&(*item).value,&(*item).name);


始终检查 fscanf的返回值,如果它小于您请求的字段数,则以下对 fscanf的调用不太可能达到您的期望。另外, *item.unititem->unit相同,请使用 item->unit,因为它更短且更干净:

int ret = fscanf(data, "%d,%lf,", &item->unit, &item->value);
if (ret != 3) { // error }


第三, %s与一系列非空格字符匹配,因此,当 fscanf读取“ John”时,它将停止,并且下一个 fscanf调用将在读取“ Snow”的同时期望一个整数。

因此,要输入带空格的字符串,请改用 fgets,并记住最后要删除换行符。

请尝试以下操作:

int main(void)
{
struct Item I;
int i;
FILE* ck;
int ret;
ck = fopen("test.txt", "r");
if (ck)
{
for (i = 0; i < 3; i++)
{
ret = load(&I, ck);
if (ret < 0)
break;
display(I, 0); //DISPLAY FUNCTION THAT READS test.txt and DISPLAYS
}
fclose(ck);
}
return 0;
}

int load(struct Item* item, FILE* data)
{
int ret = fscanf(data, "%d,%lf,", &item->unit, &item->value);
if (ret != 2) {
return -1;
}
fgets(item->name, sizeof item->name, data);
item->name[strlen(item->name)-1] = '\0';
return 0;
}

void display(struct Item item, int variableA)
{
printf("|%3d |%12.2lf| %20s |***\n", item.unit, item.value, item.name);
return;
}


它输出:

$ ./a.out
|205 | 11.20| John Snow |***
|336 | 23.40| Winter is coming |***
|220 | 34.20| You know nothing |***

关于c - C编程:读取文件并存储在struct数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40835625/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com