gpt4 book ai didi

C编程: Reading a file and storing in array of struct

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

我正在尝试通过 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

错误:程序编译时出现一些警告,但在执行代码时出现段错误。

知道为什么吗?

输出期望:OUTPUT 应从 test.txt 文件中读取,并应显示在屏幕上。

最佳答案

程序中存在多个问题:

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编程: Reading a file and storing in array of struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40835625/

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