2017-03-08 83 views
0

我试图将15x15迷宫从文本文件放入二维数组中。到目前为止,它打印出一个非常陌生的版本,所以这个迷宫看起来很奇怪,我不能在一个角色周围移动。读取文本文件的C++二维数组

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 # 
# # # # #  # # # # # 
# # # # #  # # # # # 
# # # # #  # # # # # 
# #      # # # 
# # # # # # # #  # # # 
# # # # # # # # # # # # # # # 

上面是一个函数,它应该读取文件并放入二维数组中,以便稍后调用它。下面是我试图读出来的迷宫。关于为什么打印出错的任何想法?

+0

给我们的迷宫也是如此。我会帮你的。 –

+0

在网上搜索“stackoverflow C++读取文件矩阵” –

+1

为什么一遍又一遍地打印'ch'而不给它一个新的值?你期望什么价值?这是你正在阅读的实际迷宫,是文件中的空间吗?您是否熟悉[最小完整示例](http://stackoverflow.com/help/mcve)的想法? – Beta

回答

0

这应该工作..

#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 # 
# # # # #  # # # # # 
# # # # #  # # # # # 
# # # # #  # # # # # 
# #      # # # 
# # # # # # # #  # # # 
# # # # # # # # # # # # # # #