数组打印奇怪的字符,如∟@

yan*_*234 1 c++ arrays

新的C++,制作一个tic tac toe游戏和我的阵列似乎是打印乱码,如下面的输出部分所示.我如何制作它以便我可以用char'填充数组'.'?使用c ++ 11

main.cpp中

#include <iostream>
#include "Board.hpp"

//to determine win condition:
//check row
//check column
//check diagonal
//else it's a draw

int main() {
    Board board1;
    board1.print();
    board1.makeMove(0,0,'x');
    board1.print();
    if(board1.makeMove(0,0,'x'))
        std::cout<<"true"<<std::endl;
    else
        std::cout<<"false"<<std::endl;
    std::cout<<"finished!"<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)

Board.hpp

#ifndef BOARD_HPP
#define BOARD_HPP

class Board {

private:
    char grid[3][3];
public:
    Board();
    int makeMove(int xIn, int yIn,char playerTurnIn);
    void print();

};
#endif //UNTITLED_BOARD_HPP
Run Code Online (Sandbox Code Playgroud)

Board.cpp

#include "Board.hpp"
#include <iostream>

/*default constructor which initializes an empty array with .*/
Board::Board() {
    char grid[3][3] = {{'.','.','.'},{'.','.','.'},{'.','.','.'}};
}

/*declare this in the board class

make sure to add Board:: for makeMove and print functions*/
int Board::makeMove(int xIn, int yIn,char playerTurnIn) {
    if (grid[xIn][yIn]=='.') {
        grid[xIn][yIn] = playerTurnIn;
        return true;
    }
    else {
        return false;
    }
}

void Board::print() {
    std::cout<<" 0 1 2"<<std::endl;
    for (int row = 0; row < 3; row++) {
        std::cout<<row<<' ';
        for (int col = 0; col < 3; col++) {
            std::cout<<grid[row][col]<<' ';
        }
        std::cout<<std::endl;

    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

0 1 2

0 d 1(╗

2∟@ 0 1 2

0 d 1(╗

2∟@

完了!

who*_*oan 5

问题出在你的构造函数中:

Board::Board() {
    char grid[3][3] = {{'.','.','.'},{'.','.','.'},{'.','.','.'}};
}
Run Code Online (Sandbox Code Playgroud)

在那里,您正在声明并初始化一个数组.


试试这个:

Board::Board() : grid{{'.','.','.'},{'.','.','.'},{'.','.','.'}} {}
Run Code Online (Sandbox Code Playgroud)

Ideone上测试它.谢谢@Scheff