komova

#include?<stdio.h>

#include?<cstdlib>

#include?<cstdio>

#include?<cstring>

#define?THIS_YEAR?2012

struct?DataLink? /*?用链表来保存数据?*/

{

char?Country[20];?/*?国家名称?*/

int?count; /*?运动员个数?*/

int?sumAge; /*?运动员总年龄?*/

DataLink*?Next;

};

struct?DataLink*?Head=NULL;

int?AddData(char*country,int?year);

int?DelAllData();

int?ReadFile(FILE*fp);

int?WriteFile(FILE*fp);

int?main(void)?{

FILE*?infile;?/*?输入也要从文件输入吧??*/

FILE*?outfile;

infile?=?fopen("input.txt","r");

outfile?=?fopen("output.txt","w");

if?(infile?==?NULL)

{

perror("fopen?infile?failed");

return?EXIT_FAILURE;

}

if?(outfile?==?NULL)

{

perror("fopen?outfile?failed");

return?EXIT_FAILURE;

}

fprintf(stdout,"country?|?num?of?athletes?|?aver?age?|\n");

ReadFile(infile);

WriteFile(outfile);

DelAllData();? /*?释放空间,否则会内存泄露?*/

//more?code?needed

fclose(outfile);

fclose(infile);

return?EXIT_SUCCESS;

}

int?ReadFile(?FILE*fp?)

{

char?name1[256],name2[256];?/*?如果你确定所有数据的人名都是两个单词,就可以这么做,否则就麻烦了?*/

char?country[256];

int?year;

int?retVal=0;

int?Count=0;

while(!feof(fp))

{

retVal?=?fscanf(fp,"%s%s%s%d",name1,name2,country,&year);

if(retVal<4)

return?Count;

Count++;

AddData(country,year);

}

return?Count;

}

int?WriteFile(?FILE*fp?)

{

int?Count=0;

struct?DataLink*?pTemp=Head;

fprintf(fp,"country?|?num?of?athletes?|?aver?age?|\n------------------------------------------\n");

while(pTemp?!=?NULL)

{

fprintf(fp,"%s|%d|%d|\n",pTemp->Country,pTemp->count,pTemp->sumAge/pTemp->count);

Count++;

pTemp=pTemp->Next;

}

return?Count;

}

int?DelAllData()

{

struct?DataLink*?pTemp=Head,*pLast=Head;

while(pTemp?!=?NULL)

{

pTemp?=?pTemp->Next;

delete?pLast;

pLast?=?pTemp;

}

return?1;

}

int?AddData(?char*country,int?year?)

{

struct?DataLink*?pTemp=Head,*pLast=Head;

while(pTemp!=NULL)

{

if(strcmp(pTemp->Country,country)==0)?/*?重复的国家名?*/

{

pTemp->sumAge?+=?(THIS_YEAR-year);

pTemp->count++;

return?1;

}

pTemp?=?pTemp->Next;

}

/*?走到这里表示之前没有找到相同的国家名,要新增一个链表节点?*/

struct?DataLink*?pNew?=?new?struct?DataLink();

if?(pNew?==?NULL)

{

return?0;

}

pNew->count?=?1;

strcpy(pNew->Country,country);

pNew->sumAge?=?(THIS_YEAR-year);

pNew->Next?=?NULL;

if(Head==NULL)?/*?第一个节点?*/

{

Head?=?pNew;

}

else?/*?已经有别的节点了,插到末尾?*/

{

pTemp=Head->Next;

while(pTemp?!=?NULL)

{

pLast?=?pTemp;

pTemp?=?pTemp->Next;

}

pLast->Next?=?pNew;

}

return?1;

}

结果: