I'm trying to put a 15x15 maze from a text file into a 2D array. So far, it's printing out a really stranger version so the maze looks weird and I can't move around a character.
static const int WIDTH = 15;
static const int HEIGHT = 15;
//declared an array to read and store the maze
char mazeArray[HEIGHT][WIDTH];
ifstream fin;
fin.open("lvl1.txt");
char ch;
while (!fin.eof())
{
fin.get(ch);
for(int i=0 ; i < HEIGHT ; i++)
{
for(int j=0 ; j < WIDTH ; j++)
{
fin >> mazeArray[i][j];
cout << ch;
}
}
}
fin.close();
# # # # # # # # # # # # # # #
# # # # # # # # #
# # # # # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # #
# # # # # # # # # #
# # # # # # # # #
# # # # # # # # # #
# # # # # # # O #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # #
# # # # # # # # # # #
# # # # # # # # # # # # # # #
Above is a function which is supposed to read the file and place into a 2D array so I can call it later. Below it is the maze i'm trying to read out. Any ideas on why it's printing out wrong?
This should work..
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
const int R = 15, C = 15;
char** createMatrix(char* fileName)
{
char** c_matrix = nullptr;
std::string s = "";
std::fstream file (fileName);
c_matrix = new char*[R];
for (int r = 0; r != R; ++r)
{
int cc = 0;
c_matrix[r] = new char[C];
std::getline(file, s);
for (int c = 0; c != C*2; c += 2)
{
c_matrix[r][cc] = s.at(c);
++cc;
}
}
file.close();
return c_matrix;
}
void printMatrix (char** matrix)
{
for (int r = 0; r != R; ++r)
{
for (int c = 0; c != C; ++c)
{
std::cout << matrix[r][c] << " ";
if (c == 14)
{
std::cout << std::endl;
}
}
}
}
int main()
{
char** matrix = createMatrix("matrix.txt");
printMatrix(matrix);
return 0;
}
Output:
# # # # # # # # # # # # # # #
# # # # # # # # #
# # # # # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # #
# # # # # # # # # #
# # # # # # # # #
# # # # # # # # # #
# # # # # # # O #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # #
# # # # # # # # # # #
# # # # # # # # # # # # # # #
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.