C语言:使用链表将信息通过.csv文件传递到结构
我在使用链表将.csv文件的信息传递到结构时遇到一些问题 该文件类似于:C语言:使用链表将信息通过.csv文件传递到结构,c,csv,C,Csv,我在使用链表将.csv文件的信息传递到结构时遇到一些问题 该文件类似于: 1,3.234,hello,f 3,4.2432,worldkind,o . . . 我的C程序: #include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX 50 typedef struct TP { int key; //data int atomnum; float m
1,3.234,hello,f
3,4.2432,worldkind,o
.
.
.
我的C程序:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 50
typedef struct TP
{
int key;
//data
int atomnum;
float massnum;
char nome[MAX+1];
char sym[MAX+1];
struct tableper *nseg;
struct tableper *nant;
}tp;
tp* putmemory(tp *dbase1) //function to put data to struct
{
FILE *fp1;
char *token,ch,temp[MAX];
int *tokenint,i,aux[MAX],in=-1,flag=0;
char BUFFER[MAX],*aux2;
tp *nv;
if ((fp1 = fopen("TabelaPeriodica.csv","r")) == NULL)
printf("File could not be opened \n");
while(!feof(fp1))
{
while((ch=fgetc(fp1)) != '\r')
{
temp[++in]=ch;
if(ch == ',')
{
nv->key = ++i;
token = strtok(temp[++i],",");
nv->atomnum = token;
token = strtok(NULL,",");
nv->massnum = atof(token);
token = strtok(NULL,",");
strcpy(nv->nome,token);
token = strtok(NULL,",");
strcpy(nv->sym,token);
free(nv);
}
}
}
}
int main()
{
tp *dbase1;
putmemory(dbase1);
return 0;
}
#包括
#包括
#包括
#定义最大值50
类型定义结构TP
{
int键;
//资料
国际原子;
漂浮质量;
字符名称[MAX+1];
字符符号[MAX+1];
结构tableper*nseg;
结构tableper*nant;
}tp;
tp*putmemory(tp*dbase1)//将数据放入结构的函数
{
文件*fp1;
字符*标记,ch,temp[MAX];
int*tokenint,i,aux[MAX],in=-1,flag=0;
字符缓冲区[MAX],*aux2;
tp*nv;
if((fp1=fopen(“tabelapiodica.csv”,“r”))==NULL)
printf(“无法打开文件\n”);
而(!feof(fp1))
{
而((ch=fgetc(fp1))!='\r')
{
温度[++in]=ch;
如果(ch==',')
{
nv->key=++i;
令牌=strtok(温度[++i],“,”);
nv->atomnum=令牌;
令牌=strtok(空,“”,“”);
nv->massnum=atof(令牌);
令牌=strtok(空,“”,“”);
strcpy(nv->nome,令牌);
令牌=strtok(空,“”,“”);
strcpy(nv->sym,令牌);
免费(nv);
}
}
}
}
int main()
{
tp*dbase1;
putmemory(dbase1);
返回0;
}
我的问题是:
我发现的许多问题之一是,您从未为
nv
分配内存。。。
另外,我会使用fgets
阅读整行内容,然后在上面使用strtok
同样,您必须分配
nv
,然后将dbase1
设置为它,这样您就建立了一个链表您需要为nv
分配内存
在当前代码中,nv
是未初始化的指针。你不能就这样使用它
此外,您的代码中有一个
free(nv)
,并且没有相应的nv=malloc(sizeof*nv)代码>或类似的而((ch=fgetc(fp1))!='\r')
仅在Windows上工作。我建议您将其替换为while((ch=fgetc(fp1))!='\n')
,它同样适用于Windows和所有其他操作系统。什么是struct tableper
?这其中哪一部分应该是基于链表的?我的错。。。tableper=tb[结构名称]对不起……嗯,我不知道,真的谢谢。我已经觉得很奇怪了,因为我ḿ 使用linux和“\r”也不起作用。我也喜欢fgets,但我在它的整数参数上使用什么?第一个参数是指向缓冲区的指针,第二个参数是这个缓冲区的大小,它应该对应于应该读取的最大行长度。我已经修复了这个问题。告诉我这是否正确:while(fgets(temp,sizeof(temp),fp1)!=NULL)nv=(tp*)malloc(sizeof(tp));//如果(dbase1==NULL)dbase1=nv,则为struct的每个变量生成strtok;else void insert_at_end(){printf(“\n在链表中输入元素:”);scanf(“%d”,&info);temp=(NODE*)malloc(sizeof(NODE));temp->num=info;temp->next=NULL;temp->prev=NULL;if(head==NULL){head=temp;first=temp;last=temp;}else{while(dbase1->->->next!=NULL){dbase1=dbase1=dbase1->->->->下一步;}注释区域中的dbase1->next=nv;nv->prev=dbase1;nv->next=NULL;}}代码完全不可读。请使用代码更改编辑您的问题。我在代码中看到的一点是函数定义:void insert\u at_end(){/*…*/}
不合适。在C语言中,不能在其他函数中定义函数。