#include #include #define NMAX 100 struct student { char name[30]; int mathpt; int engpt; int jpnpt; }; int main(int argc, char *argv[]) { FILE *stream; char buf[500]; struct student pt[NMAX+1]; int i, n; void dispall(struct student[]); int comp_point(const void*, const void*); if (NULL == argv[1]) { stream = stdin; } else { stream = fopen(argv[1], "r"); if (NULL == stream) { fprintf(stderr, "Cannot open data file [%s]\n", argv[1]); exit(1); } } i = 0; while (NULL != fgets(buf, sizeof buf, stream)) { if (i >= NMAX) { fprintf(stderr, "Reached to maximum number(%d)\n", NMAX); break; } n = sscanf(buf, "%29s %d %d %d", pt[i].name, &pt[i].mathpt, &pt[i].engpt, &pt[i].jpnpt); if (n == 4) { i++; } } if (stdin != stream) fclose(stream); pt[i].name[0] = 0; /* 終端の印 */ qsort(pt, i, sizeof pt[0], comp_point); dispall(pt); } void dispall(struct student pt[]) { int i, sum; for (i=0; pt[i].name[0] != 0; i++) { sum = pt[i].mathpt+pt[i].engpt+pt[i].jpnpt; printf("%2d: %-20s, %d, %d, %d | %3d\n", i+1, pt[i].name, pt[i].mathpt, pt[i].engpt, pt[i].jpnpt, sum); } } int comp_point(const void *x, const void *y) { struct student *a = (struct student *)x; struct student *b = (struct student *)y; /* a と b は構造体へのポインタ したがって、メンバへのアクセスは ピリオドでなく -> を使う */ int sum_a, sum_b; sum_a = a->mathpt + a->engpt + a->jpnpt; sum_b = b->mathpt + b->engpt + b->jpnpt; /* 引算の順番に注意 */ return sum_b - sum_a; }