input file:

1 0 0
2 1 0
0 2 1

I would like to produce this in a 3x3 array on screen. My code:

#include <fstream.h>
#include <stdlib.h>

int i, j;
int matrix[3][3]; 

int main () {

ifstream inFile;
inFile.open("input.txt");

  if (!inFile)
  {
  printf ("Unable to open input file");            
  exit(1);
  }

  for (i=0; i < 3; i++){
  for (j = 0; j < 3; j++)
    {
        inFile >> matrix[i][j];
    }
printf("%d\t", matrix[i][j]);

inFile.close ();


}

Could someone correct what I am doing wrong please?

Thank you :)

p.s. sorry for the ancient headers

printf("%d\t", matrix[j]); shd be inside the inner loop ...

Like this...?

for (i=0; i < 3; i++){

  printf("\n%f\t%f\t%f", matrix[i][j]);
  
  for (j = 0; j < 3; j++)
    {
        inFile >> matrix[i][j];
    }
}

...still doesnt work.

Inside the Inner Loop

for (i=0; i < 3; i++){

  for (j = 0; j < 3; j++)
    {
        inFile >> matrix[i][j];
        printf("\n%f\t%f\t%f", matrix[i][j]);
    }
}

like this..

hmm, still aborts for some reason?

well i'm assuming that you have done the rest of the code correctly..... and if you can tell me the error it's throwing then i might help.. but as far as ur initial qs is concerned the proposed sol will work..

Inside the Inner Loop

for (i=0; i < 3; i++){

  for (j = 0; j < 3; j++)
    {
        inFile >> matrix[i][j];
        printf("\n%f\t%f\t%f", matrix[i][j]);
    }
}

like this..

You changed the printf line from the original Andy. Above is chandra.rajat's revised code based on your revised code. Here was your original code:

for (i=0; i < 3; i++){
  for (j = 0; j < 3; j++)
    {
        inFile >> matrix[i][j];
    }
printf("%d\t", matrix[i][j]);

Originally you correctly had "%d", but you changed it to "%f" later. You want "%d" since the matrix array is integers. See top of below link for a listing of the correct specifiers for different data types. %f is for floats, %d for integers. Change it back to %d, along with chanra.rajat's suggestion and see if that works. You also stuck a bunch of extra "%f" specifiers in there. You just want one of them, and again you want "%d", not "%f". Use your original printf statement rather than the revised one, but stick it where chandra.rajat suggested.

http://www.cplusplus.com/reference/clibrary/cstdio/printf.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.