截图说明了一切,我使用的字符被正确放入数组中。但是,也会在数组中插入一些其他随机字符。我很困惑!
main.cpp:
#include "Players.h"
#include "GameLayout.h"
#include "Game.h"
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char gameBoard [3][3];
cout << "**** Welcome to Leviathan's first TicTacToe Game! ****\n\n";
Players playersObject;
playersObject.getPlayersNames();
playersObject.printPlayersNames();
GameLayout gameObject;
gameObject.printLayout();
Game gamestartObject;
gamestartObject.gameStart(gameBoard);
}
game.cpp:
#include "Players.h"
#include "GameLayout.h"
#include "Game.h"
#include <iostream>
#include <string>
using namespace std;
void Game::gameStart(char board[3][3])
{
char player1char,player2char;
size_t i,j;
cout << "Enter player 1 character :";
cin >> player1char;
cout << "Enter player 2 character :";
cin >> player2char;
int row,column;
bool isDone = false;
while(isDone == false)
{
cout << "Player 1->choose row";
cin >> row;
cout << "Player 1->choose column";
cin >> column;
board[row-1][column-1] = player1char;
cout << "Player 2->choose row";
cin >> row;
cout << "Player 2->choose column";
cin >> column;
board[row-1][column-1] = player2char;
GameLayout layout;
cout << " |1||2||3|" <<endl;
for(i=0; i<3; i++)
{
cout << i+1 << "|";
for(j=0; j<3; j++)
{
cout <<" "<<board[i][j] << " " ;
}
cout << endl;
}
}
}
Players.cpp:
#include "Players.h"
#include "GameLayout.h"
#include "Game.h"
#include <iostream>
#include <string>
using namespace std;
void Players::getPlayersNames()
{
string p1,p2;
cout << "Enter player 1 name : ";
cin >> p1;
cout << "\nEnter player 2 name : ";
cin >> p2;
_player1Name = p1;
_player2Name = p2;
}
void Players::printPlayersNames()
{
cout << "Alright " << _player1Name << " and " << _player2Name <<", the game has begun!\n\n";
}
GameLayout.cpp:
#include "Players.h"
#include "GameLayout.h"
#include "Game.h"
#include <iostream>
#include <string>
using namespace std;
void GameLayout::printLayout()
{
size_t i,j;
char board[3][3];
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
board[i][j] = '.';
}
}
cout << " |1||2||3|" <<endl;
for(i=0; i<3; i++)
{
cout << i+1 << "|";
for(j=0; j<3; j++)
{
cout <<" "<<board[i][j] << " " ;
}
cout << endl;
}
}
Game.h:
#ifndef GAME_H
#define GAME_H
class Game
{
public:
void gameStart(char board[3][3]);
private:
};
#endif // GAME_H
GameLayout:
#ifndef GAMELAYOUT_H
#define GAMELAYOUT_H
class GameLayout
{
public:
void printLayout();
private:
};
#endif // GAMELAYOUT_H
Players.h:
#ifndef PLAYERS_H
#define PLAYERS_H
#include <string>
class Players
{
public:
void getPlayersNames();
void printPlayersNames();
private:
std::string _player1Name;
std::string _player2Name;
};
#endif // PLAYERS_H
答案 0 :(得分:2)
函数中的局部非静态变量,例如gameBoard
未初始化。您需要显式初始化它,或者其内容将 indeterminate 并且读取其值将导致未定义的行为。
你可以像
那样做char gameBoard [3][3] = { ' ' };