0

我如何从 file1.txt 中读取这种类型的格式数据

ID: 123 GPA: 3.39 3.67 4.00
ID: 456 GPA: 2.39 2.67 2.90

然后将file2.txt中的数据转成这种格式:

ID: 123 GPA: 3.39 3.67 4.00 cGPA: 3.69
ID: 456 GPA: 2.39 2.67 2.90 cGPA: 2.65
4

1 回答 1

0

好吧,凯文·布恩( Kevin Boone)已经说过如何做到这一点,但是如果您不知道如何做到这一点,这里有一个简单的程序,我添加了一些注释以使代码清晰

#include <stdio.h>

int main() {
  FILE *f1 = fopen("file1.txt", "r"), *f2 = fopen("file2.txt", "w");
  // check to see if the files have been opened successfully
  if(f1 == NULL || f2 == NULL) {
    printf("There was an error opening the files");
    return 1;
  }
  // store the id and the returned value of successfully matched items of `fscanf`
  int id, x;
  // store the three gpa values as an array of doubles
  double gpa[3], cgpa;
  while(1) {
    // get the data as `int, double, double, double` from the file `file1.txt`
    x = fscanf(f1, "ID: %i GPA: %lf %lf %lf ", &id, &gpa[0], &gpa[1], &gpa[2]);
    if(x == 4) {
      // there is a match and we can do our calculation and write that line to the second file
      cgpa = (gpa[0] + gpa[1] + gpa[2]) / 3;
      // print the line to the file `file2.txt`
      fprintf(f2, "ID: %i GPA: %.2lf %.2lf %.2lf cGPA: %.2lf\n", id, gpa[0], gpa[1], gpa[2], cgpa);
    } else if(x == EOF) {
      // we have read the whole file
      break;
    } else {
      // failed to match
      printf("No match");
    }
  }
  // close the files at the end
  fclose(f1);
  fclose(f2);
  return 0;
}
于 2020-09-22T19:43:27.247 回答