C++ 使用getline将数据输入到2D数组中
对于我的一个作业,我必须使用getline创建一个2D数组。迷宫的设计是当场完成的C++ 使用getline将数据输入到2D数组中,c++,multidimensional-array,getline,C++,Multidimensional Array,Getline,对于我的一个作业,我必须使用getline创建一个2D数组。迷宫的设计是当场完成的 16 10 ################ # # # # # # #### ## ## # # ####### # ###### #E # #S# # # ### ### # # ## # # # # # ## ####### # # # ################ 这是将要测试回溯算法的示例输入之一 1610是我们迷宫中的一
16 10
################
# # # #
# # #### ## ##
# # #######
# ###### #E #
#S# # # ### ###
# # ## # # #
# # ## ####### #
# #
################
这是将要测试回溯算法的示例输入之一
1610是我们迷宫中的一列和一行
我想知道如何正确解析getline,以便使用给定的迷宫填充2D数组
另一方面,我做了一个练习,我不需要cin,而是已经有了我的阵列,我想知道如何告诉它从S开始
很抱歉,如果有问题的话,但我没有看到一个以这种格式获取2D数组,您不知道数组大小。
getline
一次只读取一行,因此,您可能需要使用for
循环依次读取每一行,并将其存储为2d数组的一行。尝试以下操作:
size_t num_rows;
size_t num_cols;
cin >> num_rows >> num_cols;
char* maze = new char[num_rows * num_cols];
for (size_t row = 0; row < num_rows; row++)
{
string line;
getline(cin, line);
if (line.size() != num_cols)
{
cerr << "Error! Size is " << line.size() << " rather than " << num_cols << endl;
exit(1);
}
for (size_t col = 0; col < num_cols; col++)
{
maze[(row * num_cols) + col] = line[col];
}
}
cout << "Maze is: " << endl;
for(int row = 0; row < num_rows; row++)
{
for(int col = 0; col < num_cols; col++)
{
cout << maze[(row * num_cols) + col];
}
cout << endl;
}
delete [] maze;
然后,确定一个随机起点:
size_t start_row, start_col;
bool found = false;
while (!found)
{
start_row = rand() % num_rows;
start_col = rand() % num_cols;
if (isspace(maze[(start_row * num_cols) + start_col]))
{
maze[(start_row * num_cols) + start_col] = 'S';
found = true;
}
}
您可以以类似的方式将端点放置在随机空白点中
人们会这样做,而且不太擅长生成随机数。确实如此,但它应该足以满足您的需要。像这样:?也许你们有同样的家庭作业。我回答了那个问题。见:直接链接。不一样,但我相信这将工作。基本上是一样的,只是我必须设置我的列和行。泰,我稍微为你做了些调整。在这里检查我的新答案。我不使用删除,是吗?仅此示例而已?当您完全处理完数组时,使用
delete
。delete
运算符与new
运算符相反。对于每个新的,您需要1个删除。我一直在研究它,并让它在一个测试迷宫中工作,在那里我知道起点,但我不知道如何使它找到一个随机的起点。你知道如何迭代并让它停留在开始吗?我不知道你说的“迭代,但停留在开始”是什么意思。但是,我添加了一些代码,可以帮助您将开始放在一个随机的空白位置。
srand(time(0));
size_t start_row, start_col;
bool found = false;
while (!found)
{
start_row = rand() % num_rows;
start_col = rand() % num_cols;
if (isspace(maze[(start_row * num_cols) + start_col]))
{
maze[(start_row * num_cols) + start_col] = 'S';
found = true;
}
}