如何在C++中有效地将数字值重新分配给字符数组

How to re-assign number values to a character array efficiently in C++

本文关键字:新分配 分配 数组 字符 C++ 有效地 数字      更新时间:2023-10-16

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