我试着做我的第一场比赛,我有问题,创造一个游戏板。我想从用户输入字符串生成一个3x3矩阵。我仍然是初学者,我非常坚持这一点。
我不知道如何在正确的地方得到这个3x3矩阵,看到代码前后的注释,您可以看到游戏板应该是什么样的,在我的代码中它看起来如何。
如果有人知道该怎么做,我会非常感激的。非常感谢。
/* 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 |
-------------
*/发布于 2022-08-11 07:41:39
矩阵构造得很好,但是当打印和代码停止时,会出现“超出范围”的错误。尝试切换到常规数组为yout游戏。
https://stackoverflow.com/questions/73316787
复制相似问题