Print maze by means of its coordinates

2

good.

I have a labyrinth like this:

*************
*          F*
*  **** * * *
*  **   * * *
*  ** *** * *
*S          *
*************

And I would like to print it in the program by means of loops, but I am getting a problem which is the following:

laberinto.c:30:39: error: invalid initializer
char laberinto[ANCHURA][ALTURA]=getc(f);

The code that is being used is the following:

#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include <stdlib.h>
#define ALTURA (7)
#define ANCHURA (13)

void imprimirLaberinto(char laberinto[ANCHURA][ALTURA]){
  int i;
  int j;

  for (i = 0; i < ANCHURA; i++) {
    for (j = 0; j < ALTURA; j++) {
      printf("%c ", laberinto[i][j]);
    }
    putchar('\n');
  }

}
int main(int argc, char *argv[]) {

  int i;
  int j;

  FILE *f; //define que variable va a ser el archivo

    f=fopen(argv[1],"r"); // Se selecciona el archivo y su modo (lectura, escritura, etc.)

  char laberinto[ANCHURA][ALTURA]=getc(f);

         if( f==NULL ){
               printf("Error al abrir el laberinto\n"); // Condicional que checa si el archivo e*iste
         }
       else
          {
                imprimirLaberinto(laberinto);
          }
}

I hope you can help me, thank you.

    
asked by Daniel Logvin 04.11.2018 в 06:19
source

1 answer

1

From the getc( ) manual:

  

int getc (FILE * stream)

     


  Reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error.

Read a single character , and you're trying to use it to read a sequence of characters; more than one .

Trying to change your code as little as possible, you could use a loop (like the one you already have) to read:

int main( int argc, char *argv[] ) {
  FILE *f;
  int error = 1;
  char laberinto[ANCHURA][ALTURA];
  int i, j, readed;

  f = fopen( argv[1], "r" );

  if( f != NULL ) {
    for( i = 0; i < ANCHURA; i++ ) {
      for( j = 0; j < ALTURA; j++ ) {
        readed = getc( f );
        if( readed == EOF ) {
          error = 1;
          break;
        }

        laberinto[i][j] = readed;
      }
    }
    error = 0;
  }

  if( error != 0 ) {
    printf( "Error al abrir el laberinto\n" );
  } else {
    imprimirLaberinto( laberinto );
  }

  return 0;
}

The error handling has been improved a bit, and the only strange is the word break , which is used to exit the current loop . It does not make sense to continue reading if the file was terminated or an error occurred.

    
answered by 04.11.2018 / 06:39
source