简体   繁体   English

从.txt文件中读取数字并将它们存储在C中的数组中

[英]Read numbers from a .txt file and store them in array in C

I've been trying to figure out how to read the scores and storing them in array. 我一直在试图弄清楚如何读取分数并将它们存储在数组中。 been trying for sometime and its clearly not working out for me. 一直在尝试,它显然不适合我。 Please help. 请帮忙。

//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;
  • You declare variables twice, once in parameter list and once in "local declarations". 您将变量声明两次,一次在参数列表中,一次在“本地声明”中。

  • The function brace is not closed. 功能支架未关闭。

  • One fscanf can only read a number of items specified by its format string, in this case 3 ( "%d%d%d" ). 一个fscanf只能读取由其格式字符串指定的多个项目,在本例中为3( "%d%d%d" )。 It reads numbers, not arrays. 它读取数字,而不是数组。 To fill an array, you need a loop ( while , or for ). 要填充数组,您需要一个循环( whilefor )。

EDIT 编辑

Okay, here's one way to do it: 好的,这是一种方法:

#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);
}

If you want to call that function just once and have it read the scores for all of the students, you should use something like this: 如果您只想调用该功能一次并让它读取所有学生的分数,您应该使用以下内容:

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]);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM