3

我一直在试图弄清楚如何读取分数并将它们存储在数组中。已经尝试了一段时间,它显然不适合我。请帮忙。

//ID    scores1 and 2
2000    62  40
3199    92  97
4012    75  65
6547    89  81
1017    95  95//.txtfile


int readresults (FILE* results , int* studID , int* score1 , int* score2);

{
// Local Declarations
int *studID[];
int *score1[];
int *score2[];

// Statements
check = fscanf(results , "%d%d%d",*studID[],score1[],score2[]);
if (check == EOF)
    return 0;
else if (check !=3)
    {
        printf("\aError reading data\n");
        return 0;
    } // if
else
    return 1;
4

2 回答 2

2
  • 您声明变量两次,一次在参数列表中,一次在“局部声明”中。

  • 函数大括号未关闭。

  • fscanf只能读取由其格式字符串指定的多个项目,在本例中为 3 ( ) "%d%d%d"。它读取数字,而不是数组。要填充数组,您需要一个循环(whilefor)。

编辑

好的,这是一种方法:

#define MAX 50
#include <stdio.h>

int readresults(FILE *results, int *studID, int *score1, int *score2) {
  int i, items;
  for (i = 0;
      i < MAX && (items = fscanf(results, "%d%d%d", studID + i, score1 + i, score2 + i)) != EOF;
      i++) {
    if (items != 3) {
      fprintf(stderr, "Error reading data\n");
      return -1; // convention: non-0 is error
    }
  }
  return 0; // convention: 0 is okay
}

int main() {
  FILE *f = fopen("a.txt", "r");
  int studID[MAX];
  int score1[MAX];
  int score2[MAX];
  readresults(f, studID, score1, score2);
}
于 2012-12-10T00:38:20.097 回答
2

如果您只想调用该函数一次并让它读取所有学生的分数,您应该使用以下内容:

int i=0;
check = fscanf(results , "%d %d %d",&id[i],&score1[i],&score2[i]);
while(check!=EOF){
        i++;
        check = fscanf(results , "%d %d %d",&id[i],&score1[i],&score2[i]);
    }
于 2012-12-10T01:03:43.140 回答