使用getline输入2D数组

时间:2012-10-20 22:22:47

标签: c++ multidimensional-array getline

对于我的一项任务,我必须使用getline来修改二维数组。迷宫设计就在现场制作。

16 10
################
#      #    #  #
# # #### ##   ##
# #      #######
# ###### #E    #
#S# #  # ### ### 
# # ## #     # #
# # ## ####### #
#              #
################

这是测试我们的回溯算法的示例输入之一。

16 10是我们迷宫的列和行。

我想知道我将如何正确解析getline,以便我的2D数组将使用给定的迷宫来填充。

在旁注上,我做了一个练习,我没有cin而已经拥有我的阵列,我想知道我怎么能告诉它从S开始。

对不起,如果有关于此的问题,但我并没有真正看到它以这种格式进入2D数组,你不知道你的数组大小。

2 个答案:

答案 0 :(得分:1)

getline一次只读一行,所以您可能要做的是使用for循环依次读取每一行并将其存储为2d的一行阵列。

答案 1 :(得分:0)

试试这个:

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;

找出start的位置:

size_t start_row, start_col;

for(int row = 0; row < num_rows; row++)
{
    bool found = false;

    for(int col = 0; col < num_cols; col++)
    {
        if (maze[(row * num_cols) + col] == 'S')
        {
            start_row = row;
            start_col = col;
            found = true;
            break;
        }
    }

    if (found)
    {
        break;
    }
}

你可以为终点做类似的事情。

如果您想将起点放在随机空白处,可以使用srandrand

首先,在程序开头播种伪随机数生成器:

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;
    }
}

您可以以类似的方式将结束点放在随机空白处。

人们会认为srandrand并不擅长生成随机数。这是事实,但它应该足以满足您的需求。

相关问题