[英]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.