读取文本文件中的C ++ 2D数组

时间:2017-03-08 02:51:07

标签: c++ arrays visual-studio function

我正在尝试将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数组中,以便稍后调用它。下面是我试图读出的迷宫。关于它为什么打印错误的任何想法?

1 个答案:

答案 0 :(得分: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 #
# #   # #   #     # #   # # # 
# #   # #   #     # #   # # # 
# #   # #   #     # #   # # # 
# #                     # # # 
# #   # # # # # #       # # # 
# # # # # # # # # # # # # # #