【问题标题】:C++ 2d Char array improperly comparingC++ 2d Char 数组不正确地比较
【发布时间】:2012-10-16 01:23:10
【问题描述】:

我正在创建一个连接四,尝试实现 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] 设置为 * 但是当我去显示这个时,它会在数组的底部显示 *,所以 place[7][col].

此外,this->place and place in the cout in 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;
}

【问题讨论】:

  • 您的问题很模糊“一直打印到 1 然后做什么?”这是一个问题的很多代码。你不能至少减少一点,以便有人能够体面地评估它。其次,您多次粘贴了一个功能,这确实使读者感到困惑。花点时间好好解释你的问题,你一定会得到答案的
  • 明确说明什么不起作用以及预期什么。你太搞砸了。我什至无法弄清楚您的代码出了什么问题
  • 不寻常的语法,通常会写成: char piece = (player==1) ? P1:P2;

标签: c++ char multidimensional-array


【解决方案1】:

一些想法:

不要delete place,你从来没有使用new来获取内存。
像这样使用条件运算符更惯用:piece = (player==1) ? P1: P2;

用于初始化、添加和显示片段的代码在这里非常有效:http://codepad.org/QIWHagMk

您能否更具体地说明您所问的问题,或者显示一个小得多的代码 sn-p 来演示您遇到的问题?

【讨论】:

    【解决方案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;
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 2015-03-26
      • 1970-01-01
      • 2021-12-06
      相关资源
      最近更新 更多