I
I
Ilya2018-11-21 14:26:15
C++ / C#
Ilya, 2018-11-21 14:26:15

How to read an array from a file in C?

intfield[n][m];
FILE *f;
f = fopen("Map 1.txt", "r");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
fscanf(f, "%d", &a[i][j]);
pole[i][j] = a[i][j];
fprintf(f,"%d",pole[i][j]);
}
printf("\n");
}
}
I'm trying to count it outputs emptiness, the array is here.
{{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0 ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{1,1 ,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 ,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1 ,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 ,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1 ,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 ,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
d_ilyich, 2018-11-21
@BeSnoMo

1. You read everything in a row as numbers, but in the file you have non-digit characters
2. You immediately print what you read back to the file.
If you want to use fscanf, then you can, for example, like this:

char c;

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

Just first format the file so that the numbers separated by commas go without the rest of the garbage.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question