gpt4 book ai didi

c - 我试图通过从文件中读取它来创建链接列表

转载 作者:行者123 更新时间:2023-11-30 14:33:01 24 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>
#define NULL 0

struct student
{
int id;
char name[20];
float marks;
struct student *next
};
typedef struct student node;
void main()
{
node *head;
void read(node *p);
void create(node *p);
int count(node *p);
void print(node *p);
head=(node *)malloc(sizeof(node));
read(head);

}
void read(node *list)
{
FILE *fp;
char filename[30];
int i;
printf("input file name:");
scanf("%s",filename);
fp=fopen(filename,"r");

while(!feof(fp))
{
create_f(list,fp);
}

}
void create_f(node *list,FILE *fp )
{
fscanf(fp,"%s %d %f",
list->name,&list->id,&list->marks);
printf("%s \t%d \t%f\n",
list->name,list->id,list->marks);

list->next=(node*)malloc(sizeof(node));
return;
}

应该读取的文件是这样的: image
但由于某些原因它读取了最后一行两次。有人可以帮助我吗?

image

如果您无法打开它,则输出为:

input file name:input.txt.txt
student01 1 95.000000
student03 3 90.000000
student05 5 86.000000
student07 7 83.000000
student09 9 98.000000
student10 10 93.000000
student08 8 92.000000
student06 6 96.000000
student04 4 93.000000
student02 2 88.000000
student02 2 88.000000

Process returned 16 (0x10) execution time : 4.043 s Press any key to continue.

1 :

最佳答案

因此,代码中的主要错误已经在几个答案中得到了很好的解释,请查看以下链接:

  1. feof
  2. fscanf

以下代码片段应该可以解决您的问题,请注意,我只有一个函数。

输入(input.txt)


student01 1 95.000000
student03 3 90.000000
student05 5 86.000000
student07 7 83.000000
student09 9 98.000000
student10 10 93.000000
student08 8 92.000000
student06 6 96.000000
student04 4 93.000000
student02 2 88.000000


解决方案

#include <stdio.h>
#include <stdlib.h>

struct student {
int id;
char name[20];
float marks;
struct student *next;
};
typedef struct student node;

void read(node *list) {
FILE *fp;
char filename[30];
printf("input file name: ");
scanf("%s",filename);
fp=fopen(filename,"r");

if(fp == NULL) return; // file doesn't exist

while(fscanf(fp, "%s %d %f", list->name, &list->id, &list->marks) == 3) {
printf("%s \t%d \t%f\n", list->name,list->id,list->marks);

list->next=(node*)malloc(sizeof(node));
}
fclose(fp);
}

int main() {
node *head;
head=(node *) malloc(sizeof(node));
read(head);
return 0;
}

输出

input file name: input.txt
student01 1 95.000000
student03 3 90.000000
student05 5 86.000000
student07 7 83.000000
student09 9 98.000000
student10 10 93.000000
student08 8 92.000000
student06 6 96.000000
student04 4 93.000000
student02 2 88.000000

关于c - 我试图通过从文件中读取它来创建链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59531322/

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