gpt4 book ai didi

C - 复制到结构中仅返回文件每一行的最后一个元素

转载 作者:太空宇宙 更新时间:2023-11-04 03:19:11 25 4
gpt4 key购买 nike

我试图将每一行分割成子字符串,用斜杠分隔并将它们加载到结构列表中,但它所做的只是输入文件每一行中的最后一个元素。

我的文件:

Adam Mickiewicz///Pan Tadeusz/Publisher 1/1833/24.99
Jules Verne///Around The World in 80 days/Publisher 1/1904/19.99
Jean-Jacques Sempe/Rene Goscinny//Little Nicholas/Publisher 2/1963/22.99

我的阅读算法:

struct element
{
char *authors[AK];
char *title;
char *publisher;
int year;
float price;

struct element *next;
};

typedef struct element Book;
char line[1024]; // Buffer
char *string; // Temporary string
char *found = "/";
Book *first = NULL;
Book *current = NULL;

while (fgets(line, sizeof(line), fp)) {
Book *new = malloc(sizeof(Book));
string = strdup(line); // Duplicate each line in file
// If encountered a separator, slice the line
while ((found = strsep(&string, "/")) != NULL) {
for (i = 0; i < AK; i++) {
new->authors[i] = strdup(found);
}
new->title = strdup(found);
new->publisher = strdup(found);
new->year = atoi(strdup(found));
new->price = atof(strdup(found));
}
if (first == NULL) {
current = first = new;
}
else {
current = current->next = new;
}
}

输出:

Authors: 24.99
24.99
24.99
Title: 24.99
Publisher: 24.99
Year: 24
Price: 24.990000
=====================
Authors: 19.99
19.99
19.99
Title: 19.99
Publisher: 19.99
Year: 19
Price: 19.990000
=====================
Authors: 22.99
22.99
22.99
Title: 22.99
Publisher: 22.99
Year: 22
Price: 22.990000
=====================

抱歉,如果之前发布过类似内容。任何建议都会有所帮助。提前致谢。

最佳答案

你的循环:

while ((found = strsep(&string, "/")) != NULL) {
for (i = 0; i < AK; i++) {
new->authors[i] = strdup(found);
}
new->title = strdup(found);
new->publisher = strdup(found);
new->year = atoi(strdup(found));
new->price = atof(strdup(found));
}

标记行直到最后一个字段(例如 24.99)并使用这个值设置/覆盖所有字段(在此过程中有很多内存泄漏)。

您不能为此使用循环,而是通过调用 x 次 strsep

一个接一个地提取每个标记

这是我(蹩脚的,未经测试的)尝试解决这个问题:

#define NEXT_TOKEN if ((found = strsep(&string, "/")) == NULL) return

for (i = 0; i < AK; i++) {
NEXT_TOKEN;
new->authors[i] = strdup(found);
}
NEXT_TOKEN;
new->title = strdup(found);
NEXT_TOKEN;
new->publisher = strdup(found);
NEXT_TOKEN;
new->year = atoi(found);
NEXT_TOKEN;
new->price = atof(found);

NEXT_TOKEN 宏避免了复制粘贴繁琐的 strsep 代码。

此外,请避免使用 new,因为它是 C++ 关键字,使您的代码仅与 C 兼容。

关于C - 复制到结构中仅返回文件每一行的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48104186/

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