如何从C中的文件扫描二维数组?

时间:2019-04-21 21:47:27

标签: c

我正在尝试从.txt文件中扫描二维数组,然后在返回平均值的函数中使用它,但是它不起作用。我对C还是很陌生,因此任何帮助将不胜感激。

我尝试直接输入行数和列数,但是什么也没出现。

(我包含了stdio.h和stdlib.h)

int main(int argc, char *argv[]){
    FILE *f;
    int A[5][5], ave;

    if ((f = fopen("program4.txt", "r")) == NULL) {
       printf ("The file could not be opened\n");
       return 1;
    }

    readfileintomatrix(A, 2, 3, f);
    ave = averagevalue(A, 2, 3);
    printf ("The average value is %d\n", ave);

    return 0;
}

void readfileintomatrix (int M[][5], int r, int c, FILE *f) {
    int i, j;

    for (i = 0; i < r; i++) {
        for (j = 0; i < c ; j++) {
            fscanf (f, "%d", &M[i][j]);
        }
    }
}

int averagevalue (int M[][5], int r, int c) {
    int i, j;
    int sum = 0;
    int average = 0;
    for (i = 0; i < r; i++) {
        for (j = 0; j < c ; j++) {
            sum += M[i][j];
        }
    }
    average = sum/ (r*c);
    return average;
}

我文件中的矩阵是

0 2 4
6 8 10

我希望输出为5,但我什么也没得到

2 个答案:

答案 0 :(得分:1)

您在readfileintomatrix函数中的循环条件不正确,因此您的readfileintomatrix函数永远不会终止:

for (i = 0; i < r; i++) {
    for (j = 0; i < c ; j++) { // << should be for(j = 0; j < c; j++) instead of i < c
        fscanf (f, "%d", &M[i][j]);
    }

将此更改为

for (i = 0; i < r; i++) {
    for (j = 0; j < c ; j++) { 
        fscanf (f, "%d", &M[i][j]);
    }

产生正确的行为。

答案 1 :(得分:0)

#include<stdio.h>  
#include<conio.h>  
int main(int argc, char *argv[]){  

    FILE *f;
    int A[5][5], ave;

    if  ((f = fopen("program4.txt", "r")) == NULL) {
       printf ("The file could not be opened\n");
       return 1;
    }
    printf ("The file is opened\n");
    A[5][5]=readfileintomatrix(A, 2 , 3 , f);
    ave = averagevalue(A, 2, 3);
    printf ("The average value is %d\n", ave);
    fclose(f);
    return 0;
}

int readfileintomatrix(int M[][5], int r , int c ,FILE *f) {
    int i, j;

    for (i = 0; i < r; i++) {
        for (j = 0; j < c ; j++) {
            fscanf(f, "%d", &M[i][j]);
            printf("hello\n");
        }
    }

    return M;
}

int averagevalue(int M[][5], int r, int c) {
    int i, j;
    int sum = 0;
    int average = 0;
    for (i = 0; i < r; i++) {
        for (j = 0; j < c ; j++) {
            sum += M[i][j];
        }
    }
    average = sum/ (r*c);
    return average;
}