gpt4 book ai didi

c++ - 将代码转换为数组并显示

转载 作者:行者123 更新时间:2023-11-28 08:27:38 25 4
gpt4 key购买 nike

我怎样才能把它变成一个数组?我需要一个板来显示空白,当用户输入时,另一个函数会用 X 或 O 填充它。目前的板子作品我想把它做成一个数组[3][3]并显示数组的内容。

void showboard(char &squareOne, char &squareTwo, char &squareThree, char &squareFour, char &squareFive, char &squareSix, char &squareSeven,
char &squareEight, char &squareNine)
{


cout << squareOne << "|" << squareTwo << "|" << squareThree << endl
<< "-+-+-"<< endl
<< squareFour << "|" << squareFive << "|" << squareSix << endl
<< "-+-+-"<< endl
<< squareSeven << "|" << squareEight << "|" << squareNine << endl;
}
}

最佳答案

您可以让 showboard() 函数接受对 chars 的 3x3 数组的引用。奇怪的参数 char (&squares)[3][3] 表示“对名为 squares 的 3x3 chars 数组的引用”。

void showboard(char (&squares)[3][3]) 
{
std::cout << squares[0][0] << "|" << squares[0][1] << "|"
<< squares[0][2] << "\n" << "-+-+-"<< "\n"
<< squares[1][0] << "|" << squares[1][1] << "|"
<< squares[1][2] << "\n" << "-+-+-"<< "\n"
<< squares[2][0] << "|" << squares[2][1] << "|"
<< squares[2][2] << std::endl;
}

int main()
{
char s[3][3] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'} };
showboard(s);
}

或者,这里有一个使用 for 循环的实现:

void showboard(char (&squares)[3][3]) 
{
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
std::cout << squares[i][j];
if(j < 2) std::cout << "|";
}
std::cout << "\n";
if(i < 2) std::cout << "-+-+-" << std::endl;;
}
}

关于c++ - 将代码转换为数组并显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3369063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com