0

Im being asked to:

Write a program that takes as input two 3x3 arrays in file "Matrices.txt", whose contents are: 3 7 1 3 4 3 6 5 0 4 1 5 2 0 4 6 1 2

I am unsure how I am to go about using fscanf to pull the numbers from the txt file and put them into two seperate 2d arrays.

This is what I got going on:

`

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

int main(){
 
  int matrixA [3][3];
  int matrixB [3][3];
  FILE *fptr;
  int i,j = 0;
  
   fptr = fopen("Matrices.txt","r");
    if(fptr == NULL){
      printf("Errpr! File was not created!");
      exit(1);
      }
  
      while(!feof(fptr)){
        fscanf(fptr,"%d%d", &matrixA[i][j]);
        i++;
        j++;
      }//while loop
    

    fclose(fptr);
    return 0;
}

`

Necro Lord
  • 11
  • 2
  • `int i,j = 0;` is equivalent to `int i; int j = 0;` I.e. it leaves `i` *uninitialized* – Some programmer dude Nov 11 '22 at 20:34
  • Also please read [Why is “while( !feof(file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong) – Some programmer dude Nov 11 '22 at 20:35
  • Besides those two issues, your code is pretty fine. – Some programmer dude Nov 11 '22 at 20:35
  • 1
    Opening a file for reading should never create a file, so `printf("Errpr! File was not created!");` seems like a strange error message. If `fopen` fails, tell the user why with `perror`: eg `if(fptr == NULL){ perror("Matrices.txt"); exit(1); }`. (But don't hard code the name.) – William Pursell Nov 11 '22 at 20:44
  • It's not at all clear to me exactly how you want to distribute the inputs into the arrays, but perhaps you are looking for `while( i < 3 && j < 3 && 2 == fscanf(fptr, "%d%d", &matrixA[i][j], &matrixB[i][j])){`. Also, make sure you initialize `i`. The line `int i,j = 0;` initializes only `j`. – William Pursell Nov 11 '22 at 23:05

0 Answers0