第8回課題の解答例

課題1

#include <stdio.h>
#include <string.h>

#define N 6

int main()
{
  struct PERSON
  {
    char family_name[20];
    char given_name[20];
    int age;
    float height;
    float weight;
  } p[N];
  int i;
  FILE *fp;

  fp=fopen("persons.txt", "r");
  for (i=0; i<N; i++)
  {
    fscanf(fp, "%s", p[i].given_name);
    fscanf(fp, "%s", p[i].family_name);
    fscanf(fp, "%d", &p[i].age);
    fscanf(fp, "%f", &p[i].height);
    fscanf(fp, "%f", &p[i].weight);
  }
  fclose(fp);

  for (i=0; i<N; i++)
  {
    printf("%s %s %d %f %f\n", p[i].given_name, p[i].family_name, p[i].age, p[i].height, p[i].weight);
  }

  return 0;
}

課題2

#include <stdio.h>
#include <string.h>

#define N 6

int main(int argc, char *argv[])
{
  int i;
  float age_total, h_total, w_total;
  struct PERSON
  {
    char family_name[20];
    char given_name[20];
    int age;
    float height;
    float weight;
  } p[N];
  FILE *fp;

  fp=fopen(argv[1], "r");
  
  for (i=0; i<N; i++)
  {
    fscanf(fp, "%s", p[i].given_name);
    fscanf(fp, "%s", p[i].family_name);
    fscanf(fp, "%d", &p[i].age);
    fscanf(fp, "%f", &p[i].height);
    fscanf(fp, "%f", &p[i].weight);
  }
  fclose(fp);

  age_total=0.0;
  h_total=0.0;
  w_total=0.0;
  for (i=0; i<N; i++)
  {
    age_total += p[i].age;
    h_total += p[i].height;
    w_total += p[i].weight;
  }
  fp=fopen(argv[2], "w") ;
  fprintf(fp, "average of age: %f\n", age_total/N);
  fprintf(fp, "average of height: %f\n", h_total/N);
  fprintf(fp, "average of weight: %f\n", w_total/N);
  fclose(fp);

  return 0;
}

Updated: