プロが教えるわが家の防犯対策術!

5人のデータ(氏名出身身長体重)をファイルから読み込み、身長の高い順にソートして別のファイルに出力するプログラムを作成せよ。というものです。c言語を習っているのですが全然付いていけてないので教えていただきたいです。読み込みdeta.txt,書き込みresult.txtです。

A 回答 (1件)

#include <stdio.h>


#include <stdlib.h>

typedef struct {
 char name[16];
 char birthplace[8];
 float height;
 float weight;
} data_t;

int cmp(const void* p, const void* q) {
 return((data_t*)q)->height - ((data_t*)p)->height;
}

int main(void) {

 FILE* fp;
 data_t people[5];

 if ((fp = fopen("deta.txt", "r")) == NULL) {
  return EXIT_FAILURE;
}

 for (int i = 0; i < 5; i++) {
  fscanf(fp, "%s %s %f %f\n", people[i].name, people[i].birthplace, &people[i].height, &people[i].weight);
 }
 fclose(fp);

 qsort(people, 5, sizeof(data_t), cmp);

 if ((fp = fopen("result.txt", "w")) == NULL) {
  return EXIT_FAILURE;
 }

 for (int i = 0; i < 5; i++) {
  fprintf(fp, "%s %s %f %f\n", people[i].name, people[i].birthplace, people[i].height, people[i].weight);
 }
 fclose(fp);

 return EXIT_SUCCESS;
}
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!