首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >输入字符串中的C++ 3x3棋盘打印

输入字符串中的C++ 3x3棋盘打印
EN

Stack Overflow用户
提问于 2022-08-11 07:25:45
回答 2查看 60关注 0票数 0

我试着做我的第一场比赛,我有问题,创造一个游戏板。我想从用户输入字符串生成一个3x3矩阵。我仍然是初学者,我非常坚持这一点。

我不知道如何在正确的地方得到这个3x3矩阵,看到代码前后的注释,您可以看到游戏板应该是什么样的,在我的代码中它看起来如何。

如果有人知道该怎么做,我会非常感激的。非常感谢。

代码语言:javascript
复制
/* Gameboard should look like this when input is "1 1 4 2 1 4 2 3 5":
=============
|   | 1 2 3 |
-------------
| 1 | 1 1 4 |
| 2 | 2 1 4 |
| 3 | 2 3 5 |
=============
*/


#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;
using Board = std::vector<vector<int>>;

const unsigned int BOARD_SIDE = 3;
const unsigned char EMPTY = ' ';

void initBoard(Board& board) { // start questions + vector formation

    while (true) {
            cout << "Select start (R for random, I for input): ";
            string start;
            cin >> start;
            if (start == "i" or start == "I") {
                cout << "Input: ";
                string input = "";
                cin.ignore();
                getline(cin, input);

                istringstream is { input };
                vector<vector<int>> board(3, vector<int>(3)); // board is now 2D vector including 9 user input values

                for (auto& row : board)
                {
                    for(auto& column : row)
                    {
                        is >> column;
                    }
                }
                    for(const auto& row : board)
                    {
                        for (const auto column : row)
                        {
                            cout << column << " ";
                        }
                            cout << "\n";
                    }
                break;
                }
      }
}

void printBoard(const Board& board)
{
    // prints a board vector whose elements are vectors
    cout << "=============" << endl;
    cout << "|   | 1 2 3 |" << endl;
    cout << "-------------" << endl;
    for(unsigned int row = 0; row < BOARD_SIDE; ++row)
    {
        cout << "| " << row + 1 << " | ";
        for(unsigned int column = 0; column < BOARD_SIDE; ++column)
        {
            if(board.at(row).at(column) == 0)
            {
                cout << EMPTY << " ";
            }
            else
            {
                cout << board.at(row).at(column) << " ";
            }
        }
        cout << "|" << endl;
    }
    cout << "=================" << endl;
}

int main()
{
    Board board;
    initBoard(board);
    printBoard(board);
}

/* But it looks like this:
1 1 4 
2 1 4 
2 3 5 
=============
|   | 1 2 3 |
-------------
*/
EN

Stack Overflow用户

发布于 2022-08-11 07:41:39

矩阵构造得很好,但是当打印和代码停止时,会出现“超出范围”的错误。尝试切换到常规数组为yout游戏。

票数 -2
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73316787

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档