c语言将txt中的数据存入数组
本来有数据,第一列是id号,第二列是属性值(int类型),我想从中读取相同id的属性然后存入一个数组中,进而进行其他的运算,该怎么写代码呢?图1是原数据,我想要的效果大概...
本来有数据,第一列是id号,第二列是属性值(int类型),我想从中读取相同id的属性然后存入一个数组中,进而进行其他的运算,该怎么写代码呢?图1是原数据,我想要的效果大概如图2,只是id号不用显示了,只显示属性值的数组就行了
展开
展开全部
#include <stdio.h>
#include <malloc.h>
#define MAXSIZE 80
typedef struct data {
unsigned id;
int attribute;
}Data;
typedef struct node {
unsigned id;
int attributes[MAXSIZE];
size_t size;
struct node *next;
}*pNode,*LinkList;
LinkList GetNewList() {
pNode head = (pNode)malloc(sizeof(struct node));
if(head == NULL) return NULL;
head->id = 0;
head->size = 0;
head->next = NULL;
return head;
}
void Additive(LinkList head,Data data) {
pNode q,p = head;
while(p->next) {
if(p->next->id == data.id) {
p->next->attributes[p->next->size] = data.attribute;
++p->next->size;
return;
}
p = p->next;
}
q = (pNode)malloc(sizeof(struct node));
q->id = data.id;
q->attributes[0] = data.attribute;
q->size = 1;
q->next = p->next;
p->next = q;
}
void Show(LinkList head) {
int i;
pNode p = head->next;
while(p) {
printf("%u : ",p->id);
for(i = 0; i < p->size; ++i)
printf("%d ",p->attributes[i]);
printf("\n");
p = p->next;
}
}
int main() {
int i;
Data data;
FILE *inf,*outf;
char infilename[] = "indata.txt";
char outfilename[] = "outdata.txt";
pNode p;
LinkList list = GetNewList();
if(list == NULL) return 1;
if((inf = fopen(infilename,"rt")) == NULL) {
printf("无法打开文件:%s\n",infilename);
return 2;
}
while(fscanf(inf,"%u%d",&data.id,&data.attribute) == 2)
Additive(list,data);
fclose(inf);
Show(list);
if((outf = fopen(outfilename,"rt")) == NULL) {
printf("无法打开文件:%s\n",outfilename);
return 3;
}
for(p = list->next; p; p = p->next) {
fprintf(outf,"%u ",p->id);
for(i = 0; i < p->size; ++i)
fprintf(outf,"%d ",p->attributes[i]);
fprintf(outf,"\n");
}
fclose(outf);
return 0;
}
更多追问追答
追问
我运行后show函数没有输出并且outdata文件里没有东西啊
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询