gpt4 book ai didi

C++ 2d Char 数组比较不正确

转载 作者:行者123 更新时间:2023-11-30 04:23:57 27 4
gpt4 key购买 nike

我正在创建一个连接四,试图实现放置功能,添加到特定列中的最低行。这是董事会的初始化

Board::Board()
{
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
place[i][j] = EMP; // EMP is a const char = '-'

cout << "Initalized.\n";
}

出于某种原因,这段代码一直运行到 i = 1,然后将 place[1][col] 设置为 *但是当我去显示它时,它在数组底部显示 *,所以放置 [7][col]。

此外,this->place and place in the cout at the beginning never give me the output of '-' which it should be.

int Board::add(int player, int col)
{
char piece;
col--; // Dealing with array starting at 0, not 1
(player==1) ? piece = P1: piece = P2; // Character defining players piece
int i;

for (i = 7; i >= 0; i--)
{

cout << "this - " << this->place[i][col] << endl;
cout << "place - " << place[i][col] << endl;
if(place[i][col] == EMP)
{
cout << "Empty looks like " << place[i][col] << "\ti: " << i << endl;
place[i][col] = piece;
system("pause");
return i;
}else
{
cout << "not EMP - " << place[i][col] << endl;
system("pause");
}
}

return 0;
}

最佳答案

你将一个 char 传递给你的 int 函数,它将数字转换为一个 char 变量(给你垃圾)。我稍微重写了函数,一切似乎都正常。

int Board::add(int player, char col)
{
char piece;
int Num;
Num = atoi(&col);
cout << Num << endl << endl;
Num--; // Dealing with array starting at 0, not 1
(player==1) ? piece = P1: piece = P2; // Character defining players piece
int i;

for (i = 7; i >= 0; i--)
{

cout << "this - " << this->place[i][Num] << endl;
cout << "place - " << place[i][Num] << endl;
if(place[i][Num] == EMP)
{
cout << "Empty looks like " << place[i][Num] << "\ti: " << i << endl;
place[i][Num] = piece;
return i;
}else
{
cout << "not EMP - " << place[i][Num] << endl;
}
system("pause");
}

return 0;
}

希望这对您有所帮助。

关于C++ 2d Char 数组比较不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13075722/

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