簡體   English   中英

在C ++中打印2D char數組

[英]Printing a 2D char array in C++

所以我的代碼有問題,我無法查明。 簡而言之,我想以網格格式用c ++打印2D char數組的內容。 我的代碼如下(請記住,我不想更改代碼的結構,只是找到為什么我沒有得到期望的結果):

#include <iostream>
#include <string>

using namespace std;

void drawBoard(char board[3][4])
{
    int j = 0;

    for (int i = 1; i < 12; i++)
    {
        if ((i % 4) == 1 || (i % 4) == 2)
        {
            cout << " " << board[i][j] << " |";
        }
        else if ((i % 4 == 3))
        {
            cout <<  " " + board[i][j] << endl;
        }
        else
        {
            cout << "---+---+---" << endl;
            j += 1;
        }
    }
}

int main()
{
    char board[3][4] = { {' ', ' ', ' ', '\0'}, {' ', ' ', ' ', '\0'}, {' ', 
    ' ', ' ', '\0'} };
    drawBoard(board);

    cin.get();
}

我期望給我的是一個基本的井字游戲網格,其中X和O都留有空白。 取而代之的是,我得到的是一個預期的網格,在某些正方形中放置了隨機字符,無論我進行多少次調整都會得到相同或相似的結果,但我不明白為什么。 任何幫助將不勝感激(最好也不包括基本的c ++之外的函數,循環等內容,因為我還沒有學到這些,即使知道了它們也無法在我們的作業中使用它們)。

檢查數組范圍:

char board[3][4]

然后您有:

board[i][j]  ->  board[1,2,3,5,6,7,9,10,11][j] 

不管是什么i%4的,什么是放boardi不是i%3

使用以下兩種結構之一:

for i
   for j
      board[i][j]

要么

for i
   ((char*)board)[i]

我已經編輯了您的代碼:

#include <iostream>
#include <string>

using namespace std;

void drawBoard(char board[3][4])
{
    for (int i = 0; i < 12; i++)
    {
        if(i%4!=3)
        {
            cout<<" "<<board[i/4][i%4]; // board[0 to 2][0 to 2, 3 skept]
            if(i%4<2)
                cout<<" |";
        }
        else
        {
            if(i/4<2)
                cout<<endl<< "---+---+---";
            cout<<endl; // new line
        }
    }
}

int main()
{
    char board[3][4] = { {'x', 'o', 'x', '\0'}, {'o', 'x', 'x', '\0'}, {'o', 
    'o', 'x', '\0'} };
    drawBoard(board);

    cin.get();
}

結果:

 x | o | x
---+---+---
 o | x | x
---+---+---
 o | o | x

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM