C 2D char阵列不当比较

C++ 2d Char array improperly comparing

本文关键字:比较 阵列 2D char      更新时间:2023-10-16

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

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,然后将位置[1] [col]设置为 *但是当我去显示此内容时,它在数组的底部显示 * *

也是这个 ->一开始就在cout中的位置和放置,永远不要给我输出。

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

希望这会有所帮助。

一些想法:

不要delete place,您从未使用new获得内存。
这样使用有条件的操作员是更惯用的: piece = (player==1) ? P1: P2;

初始化,添加和显示的代码在这里几乎可以使用:http://codepad.org/qiwhagmk

您是否可以更具体地说出您的要求或显示一个较小的代码片段,以证明您看到的问题?