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

时间:2012-10-25 19:22:18

标签: c++ char multidimensional-array

我创建了一个connect four,尝试实现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,然后将place [1] [col]设置为* 但是当我去显示它时,它显示数组底部的*,所以放置[7] [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;
}

2 个答案:

答案 0 :(得分:2)

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

希望这有帮助。

答案 1 :(得分:0)

一些想法:

不要delete place,你从未使用new来获取记忆 使用像这样的条件运算符更加惯用:piece = (player==1) ? P1: P2;

初始化,添加和显示片段的代码几乎可以在这里工作:http://codepad.org/QIWHagMk

您可以更具体地了解您所询问的内容,还是展示一个更小的代码片段来演示您所看到的问题?