gpt4 book ai didi

C编程。文件 I/O、链接列表和结构

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

我的作业要求我编辑提供给我的 C 程序,以便它可以从文本文档中读取,其中每一行如下所示:

int%char%char%Double%int%int%int

在文件末尾有任意行数和一个空行。

这个文本文件被传递给这个程序:

#include <stdlib.h> 
#include <stdio.h>
struct node{
int element;
struct node * next;
};
// node structure
struct node * head = NULL; // head node
void add_node(int num) {
if (head == NULL){
head = (struct node *) malloc(sizeof(struct node));
head->element = num;
}
else{
struct node * p = head;
while(p->next != NULL)
p = p->next;
p->next = (struct node *) malloc(sizeof(struct node));
p->next->element = num;
}
}
void print_list() {
struct node * p = head;
while(p != NULL){
printf("%d ", p->element);
p = p->next;
}
}
void free_list() {
struct node * p = head;
while(head != NULL){
p = head->next;
free(head);
head = p;
}
}
int main(int argc, char const *argv[]) {
int n, i;
for (i = 0; i < 10; i++) {
scanf("%d", &n);
add_node(n);
}
print_list();
free_list();
return 0;
}

我需要编辑此程序以将文件中的 7 个字段(ID、类别、详细信息、金额、年、月、日)包含在结构节点中。然后让它从文本文件(现在是 File_name.txt)中读取,在结构节点中添加它们之间没有 % 分隔符的字段,然后按这样的顺序打印出来(RecordID: (ID) Category: (category) Amount : $(amount) Date: (Month)-(Day)-(Year) Detail: (detail)) 并在程序终止前释放所有指针。我不希望你们都为我做作业,只是我不知道 C 编程是如何工作的,我需要这样做,所以如果有人能帮助我指出正确的方向,告诉我如何去做这件事不胜感激。

最佳答案

据我所见。

  • 您将不得不使用文件中的指定变量创建您自己的结构。

  • 读取每一行并智能地解析它们...函数 strtok 应该能够在 C 中执行此操作。

  • 使用不应该太难编写的函数提取变量以存储在创建的结构

  • 其余的您可以或应该能够处理

这可能没有你希望的那么有用,但你可以试着让我理解,这样我可以帮助做得更好

关于C编程。文件 I/O、链接列表和结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36803055/

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