aishere
aishere

Reputation: 53

Find specific character in txt file for maze

I'm trying to setup a function that gets the Entrance of a maze from a text file, the char in the txt file is an 'E'. This needs to be used as the starting position for the player but I'm not sure how to identify a certain character in a text file.

Here is the code for reading in the file and printing it but I'm not sure how to pick out the Entrance and assign a value to it.

void Floor::printToScreen()
{
ifstream f("FloorA.txt");
string str;
int cols = 0;
int rows = 0;

char maze[20][30];

int line = 0;
while(getline(f, str)){
    const char * chars = str.c_str();
    for(int i = 0; i<str.length(); i++){
        maze[line][i] = chars[i];
    }
    cols = str.length();
    line++;
    rows++;
}
for (int i=0; i<line; i++){
    for(int j=0; j<rows; j++){
        cout << maze[i][j] << "";
    }
    cout << endl;
}
cout << "Rows: " << rows << " Columns: " << cols;
}

FloorA txt file:

##############################
#      K                     #
#  ############## ### ###  # #
#      K    #   # #C# #K#  # #
# ######### # A # # # # #  # #
#      K    #   #          # #
# ############D#####D####### #
#                            #
#   C         G        C     #
#                            #
# ######D##############D#### #
#      #  C         #K#    # #
# #### ######## #   # #      #
# #K   #      # ### # # #### #
# # ## # #### #   # # #    # #
E # ## # #    ### # # #### # # 
# #    # #K           D    # #
# #D#### ################### #
#                    K       #
##############################

This was discussed briefly in another post, but please don't mark as duplicate as I'm still confused on the implementation so I wanted to ask a more specific question here.

Upvotes: 0

Views: 272

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57728

Try this:

bool entrance_found = false;
unsigned int entrance_row = 0;
unsigned int entrance_column = 0;
for (row = 0; row < MAX_ROWS; row++)
{
  for (column = 0; column < MAX_COLUMNS; ++column)
  {
    if (maze[row][column] == 'E')
    {
      entrance_found = true;
      entrance_row = row;
      entrance_column = column;
      break;
    }
  }
  if (entrance_found)
  {
    break;
  }
}

This is a standard idiom for searching a matrix or 2D array.

Note how the row and column of the entrance are saved into entrance_row and entrance_column when the 'E' is found.

The variable entrance_found is used to exit out of the outer loop. Although it is not necessary, it does save time.

Upvotes: 1

Related Questions