[英]C++ 2D array from read text file
我正在尝试将文本文件中的15x15迷宫放入2D数组中。 到目前为止,它已经打印出了一个非常陌生的版本,因此迷宫看起来很奇怪,我无法绕过角色。
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 #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # #
# # # # # # # # # # #
# # # # # # # # # # # # # # #
上面是一个应该读取文件并将其放入2D数组的函数,因此我以后可以调用它。 在它下面是我要读出的迷宫。 关于为什么打印错误的任何想法?
这应该工作..
#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;
}
输出:
# # # # # # # # # # # # # # #
# # # # # # # # #
# # # # # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # #
# # # # # # # # # #
# # # # # # # # #
# # # # # # # # # #
# # # # # # # O #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # #
# # # # # # # # # # #
# # # # # # # # # # # # # # #
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.