题目:把a.txt文件中的内容,同一个地点的姓名归为一类。输出的时候按类输出。并且计算每类地址中姓名的总数。
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define N 100
- typedef struct PERSOONSTRU
- {
- char name[256];
- }
- PERSOON;
- typedef struct FIERSTRU
- {
- int count;// 数据的总数
- char add[256];// 数据的地址
- PERSOON p[256];
- }FIER;
- int main()
- {
- FIER *data=NULL;
- char tempadd[256];
- char tempname[256];
- int m=0;
- int j=0;
- int i=0;
- FILE *pFile;
- data = (FIER*)malloc(sizeof(FIER)*N);
- memset(data, 0, sizeof(FIER)*N);
- // 在c语言中函数前面是不可以插入临时变量的
- pFile=fopen("a.txt", "rb");
- if (!pFile)
- {
- fclose(pFile);
- exit(0);
- }
- while(!feof(pFile))
- {
- memset(tempadd, 0, 256);
- memset(tempname, 0, 256);
- fscanf(pFile, "%s%s", tempname, tempadd);
- // 执行fscanf后data[0].count变为一个不确定的数
- // 当把前面的两个函数变为memset(tempadd,0, strlen);
- for (i=0; i<m; i++)
- {
- // 存在的类别
- if (0==strcmp(data[i].add, tempadd))
- {
- strcpy(data[i].p[data[i].count].name, tempname);
- data[i].count++;
- break;
- }
- }
- // 新的类别
- if (i==m)
- {
- strcpy(data[m].add,tempadd);
- strcpy(data[i].p[data[m].count].name, tempname);
- data[m].count++;
- m++;
- }
- }
- for (i=0;i<m; i++)
- {
- // 输出种数
- printf("%d/n", data[i].count);
- printf(data[i].add);
- printf("/n");
- for (j=0; j<data[i].count; j++)
- {
- printf("%s/n", data[i].p[j].name);
- }
- printf("/n");
- }
- free(data);
- system("pause");
- return 0;
- }
文件中内容为:姓名 地点
结果: