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

Array prints weird characters such as ∟ @

本文关键字:例如 字符 打印 数组      更新时间:2023-10-16

C++新手,制作井字游戏,我的数组似乎打印了胡言乱语,如下面的输出部分所示。 如何做到这一点,以便我可以用字符'.'填充数组?使用 c++ 11

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

板.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

董事会.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;
}
}

输出:

0 1 2

0 天  1 ( ╗

2 ∟ @ 0 1 2

0 天  1 ( ╗

2 ∟ @

完成!

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

Board::Board() {
char grid[3][3] = {{'.','.','.'},{'.','.','.'},{'.','.','.'}};
}

在那里,您正在声明和初始化一个新数组。


试试这个:

Board::Board() : grid{{'.','.','.'},{'.','.','.'},{'.','.','.'}} {}

在 Ideone 上进行测试。谢谢@Scheff