簡體   English   中英

從.txt文件中讀取數字並將它們存儲在C中的數組中

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

我一直在試圖弄清楚如何讀取分數並將它們存儲在數組中。 一直在嘗試,它顯然不適合我。 請幫忙。

//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;
  • 您將變量聲明兩次,一次在參數列表中,一次在“本地聲明”中。

  • 功能支架未關閉。

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

如果您只想調用該功能一次並讓它讀取所有學生的分數,您應該使用以下內容:

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