【问题标题】:Read numbers from a .txt file and store them in array in C从 .txt 文件中读取数字并将它们存储在 C 中的数组中
【发布时间】:2012-11-27 10:10:18
【问题描述】:

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

//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;

【问题讨论】:

  • 你会一直知道你会读多少乐谱吗?如果没有,那么您将需要使用 WHILE 循环,直到完成。您打算多次调用此函数(每个玩家一次)还是只调用一次?
  • 是的,总是学生 ID 和分数 1 和分数 2。最多 50 分超出我将不得不打印一条消息,例如“该文件包含超过 50 名学生!”并终止程序。
  • @KexyKathe:他的意思是,是否设置了行数;在这种情况下 5. 此外,如果您在此处编写的文件中有标题,则也需要注意它 - 读取并丢弃。
  • .txt 文件只包含数字。

标签: c arrays file store


【解决方案1】:
  • 您声明变量两次,一次在参数列表中,一次在“局部声明”中。

  • 函数大括号未闭合。

  • 一个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);
}

【讨论】:

  • #define MAX=50; for (i
  • 不,这不是for 语法;但它更近了。如果您在此处使用while 而不是for,那么这是朝着正确方向迈出的一大步。现在您必须通过将这三个值放在数组中的正确位置来填充循环体。 (你也可以直接读入数组元素,但我想这是一个高级练习。)
  • 我还是不明白。是这个吗? while(i
  • @KexyKathe:好了,为你解决了。详细询问你不明白的事情。
  • "stderr" 抱歉这是什么
【解决方案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]);
    }

【讨论】:

  • 好的,那么您只需要在每次迭代中使用数组的索引即可。只需编辑答案
  • 我需要丢弃 ID,所以我添加一个 %*d 对吗?我的函数头应该是 int readresults (FILE* AG_midterm ,int* score1[] , int* score2[])?
  • 别忘了学生证
  • 但我需要丢弃它,因为我只需要分数来平均它们并按降序打印。
  • 哦,是的,在那种情况下你不需要它
猜你喜欢
  • 2020-05-25
  • 2014-08-14
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-25
  • 2012-11-22
  • 1970-01-01
相关资源
最近更新 更多