给定一个字符串,如何创建一个二维字符数组?

How to create a 2D-Array of chars given a string?

给出这个字符串(或任何字符串):“# ####\n# #\n# ## #\n# #\n### ##\n”, 我如何为我的数据结构和算法寻找最短路径迷宫求解器 class。给定这个字符串(或任何字符串),我如何从中创建一个二维数组?这样,我就可以遍历二维数组,如果它是空白,我可以创建一个新顶点。

比如这个

"#####\n##\n####\n##\n#####\n"

应该像这样存储在二维数组中:

 # ####

 #    #

 # ## #

 #    #

 ### ##

我尝试执行此操作,但没有打印出正确的内容。

char ** grid;
for(int i = 0; i < maze.size(); i++){
    grid[i] = new char[numCols];
    for(int j = 0; j != '\n'; j++){
        cin >> grid[i][j];
    }
}

不确定您处理的行数是固定的。下面的示例是保守的,它假设您事先不知道行数并且每行可以有不同的长度,因此它使用 vector 的向量 string.

如果你事先知道大小,你可以用数组替换它。评论应该使行为明确。

#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;

int main()
{
   const char *s = "# ####\n#    #\n# ## #\n#    #\n### ##\n";

   istringstream is(s);  // associate the input string with an input stream

   vector<string> result;  // use string for each line because a vector of characters is a string

   string line;
   while(getline(is, line)) // use stream library to read until next \n character
        result.push_back(line);  // add line

   // demonstrate results
   for (size_t i = 0; i < result.size(); ++i) {
       for (size_t j = 0; j < result[i].length(); ++j)
           cout << result[i][j];
       cout << "\n";
   }

   return 0;
}