Okie dokie,这是我第一次在这里发布信息,如果我的格式不好,请原谅我。我目前在第二堂C ++课中,我们的任务是使用1D数组创建井字游戏。我们的教授想要它的方式要求数组使用字符而不是整数。我有自己的游戏代码,但是我希望能够在某人获胜或并列后玩新游戏。为了做到这一点,我需要摆脱现在存储在我的数组中的X和O。我的麻烦是尝试创建一个循环以适当地重新分配字符值。
我对数组的概念完全陌生,至少可以说我的理解仍然很脆弱。如果我完全缺少可以简化此操作的内容,请帮帮我!目前,它只是打印出随机的ASCII字符,因为它不知道数字应该被解释为字符。有任何想法吗? :)
更新:我发现了一种重新分配值的蛮力方式,但是看起来好像有一种更好的方式。
// This is the initial board setup
char theBoard[SIZE] = {'0', '1', '2', '3', '4', '5', '6', '7', '8'};
// It is re-assigned values of 'X's and 'O's throughout the game
// By the end it looks more like : {X, O, X, O, O, X, X, X} if you can imagine
// My brute force method looks like this:
void initializeBoard(char theBoard[], int SIZE)
{
theBoard[0] = '0';
theBoard[1] = '1';
theBoard[2] = '2';
theBoard[3] = '3';
theBoard[4] = '4';
theBoard[5] = '5';
theBoard[6] = '6';
theBoard[7] = '7';
theBoard[8] = '8';
}
// And the for loop I was trying to use looked like this:
void initializeBoard(char theBoard[], int SIZE)
{
for(int i = 0; i < SIZE; i++)
{
theBoard[i] = i;
}
}
在C ++中,0
和'0'
是两个不同的东西。一个是整数值0,一个是整数值48,恰好与字符'0'的ASCII码相同。]
您试图编写的循环很简单:
void initializeBoard(char theBoard[], int SIZE)
{
for(int i = 0; i < SIZE; i++)
{
theBoard[i] = '0' + i;
}
}