从一个txt文件中读取两个矩阵

时间:2013-02-18 22:55:59

标签: c

我遇到一项任务有困难。

我需要从文本文件中读取两个矩阵并将它们相乘。

问题是我知道如何读取一个矩阵,但我不明白如何读取文件中两个空格分隔的两个矩阵。(/ p>

Matrix.txt:

1 2 3  1 2 3
4 5 6  4 5 6
7 8 9  7 8 9

也许有人可以解释我该怎么做。

现在我正在尝试阅读第一个矩阵:

#include <stdlib.h>
#include <stdio.h>

int main(){
FILE *fp;
int eSk = 0, sSk = 0,
matrix1[10][10] = {0}, i, j;
char c;
fp = fopen("matrix.txt", "r+");
while(!feof(fp)) {
    while(getc(fp) != ' ') {
         fscanf(fp, "%d", &matrix1[eSk][sSk]);
         sSk++;
    }
    eSk++;
}

for(i = 0; i < eSk; i++) {
      for(j = 0; j < sSk; j++) {
            printf("%d ", matrix1[eSk][sSk]);
      }
      printf("\n");
}

puts("");

system("pause");
return 0;
}

出了什么问题?

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

你需要跳过第二个矩阵,同时阅读第一个矩阵,反之亦然。试试这个:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  FILE *file;
  int matrixA[3][3], matrixB[3][3];
  int garbage[3];
  int i, j, k;

  i = j = k = 0;
  file = fopen("matrix.txt", "rt");

  /* Read the first matrix */
  for (i = 0; i < 3; i++) {
     for (j = 0; j < 3; j++) {
        fscanf(file, "%d", &matrixA[i][j]);
     }
     /* Skip the second matrix */
     for (k = 0; k < 3; k++) fscanf(file, "%d", &garbage[k]);
  }

  /* Reposition the stream */
  fseek(file, 0, SEEK_SET);

  /* Read the second matrix */
  for (i = 0; i < 3; i++) {
     /* Skip the first matrix */
     for (k = 0; k < 3; k++) fscanf(file, "%d", &garbage[k]);      
     for (j = 0; j < 3; j++) {
        fscanf(file, "%d", &matrixB[i][j]);
     }
  }

  /* Multiply them ... */

  /* Show first matrix */
  for (i = 0; i < 3; i++) {
     printf("\n");
     for (j = 0; j < 3; j++) {
        printf(" %d ", matrixA[i][j]);
     }
  }
  printf("\n");

  /* Show second matrix */
  for (i = 0; i < 3; i++) {
     printf("\n");
     for (j = 0; j < 3; j++) {
        printf(" %d ", matrixB[i][j]);
     }
  }
  return 0;
}

答案 1 :(得分:0)

如果字符串的格式是标准化的,您可以一次读取两个矩阵。对于上面的示例,请找到如下修改后的版本。

int main(){
FILE *fp;
int eSk = 0, sSk = 0, i, j;

int  mat1[3][3], mat2[3][3];
char line[256];

char c;
fp = fopen("matrix.txt", "r+");
if(NULL == fp) {
    printf("Can't open the file\n");
    exit(-1);
}

// Read one line
fgets(line, 256, fp);
while(!feof(fp)) {
    // Convert line to array
    sscanf(line,"%d %d %d  %d %d %d", &mat1[eSk][0], &mat1[eSk][1], &mat1[eSk][2], &mat2[eSk][0], &mat2[eSk][1], &mat2[eSk][2]);
// Increment counter
eSk++;
//Read next line
fgets(line, 256, fp);
}

printf("Matrix1\n");

for(i = 0; i < eSk; i++) {
  for(j = 0; j < 3; j++) {
        printf("%d ", mat1[i][j]);
  }
  printf("\n");
}

printf("Matrix2\n");

for(i = 0; i < eSk; i++) {
  for(j = 0; j < 3; j++) {
        printf("%d ", mat2[i][j]);
  }
  printf("\n");
}

puts("");

system("pause");
return 0;
}