如何在C++中有效地将数字值重新分配给字符数组
How to re-assign number values to a character array efficiently in C++
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;
}
}
相关文章:
- C++ 如何在将新对象分配给另一个对象时创建新对象
- 如何增加以前由新运算符分配的 C++ std::list 数组的大小?
- 为模板参数类型中的新对象分配内存
- 新运算符分配的大小大于声明的大小.为什么
- 在C++中分配分配
- 为什么支撑初始化分配分配填充垃圾变量
- C 新操作员分配新内存
- 新不分配内存?
- 如果我的C++“新”内存分配失败,如何找出返回值
- 我可以用新的分配内存块吗?
- COM / DCOM:服务器存根不会为现有接口中的新方法分配内存
- 在线程在 C++ 中完成后将新任务分配给线程
- 只能使用CUDA中的新运算符分配有限的内存
- 与将新内容分配给向量的指针斗争
- 确定C++中新运算符分配的内存大小
- 按新内存分配
- 是否有必要使用 'new' 将新指针分配给与指向同一结构的先前存在的指针相同的结构?如果是这样,为什么?
- 用于新运算符分配的公共内存
- boost::io_service post方法是否引起新的分配?
- 如何在C++中检索由新运算符分配的对象的地址