0

I am new to C++ and I am making a program for class. The program is a game of Tic Tac Toe between two people. I have have already completed a version of the program which does not use functions and I have trying to make use of them.

I would like to edit an array within a function and output the function to be used later in the program.

Here's the code;

// This is a assessment project which plays ticTacToe between two players.

#include <iostream>

using namespace std;

int main() {

    void displayBoard(char ticTacToeGame[][3]); // sets up use of displayBoard()
    char userPlay(); // sets up use of userPlay()
    char addplayToBoard(char play, char ticTacToeGame[][3] ); // sets up use of addPlayToBoard()


    char ticTacToeGame[3][3] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; // game board array


    // declaration of variables
    char play;

    displayBoard(ticTacToeGame); // displays the board to user
    play = userPlay(); // gets users play and stores it as a char

    return 0;
} // end of main()

// function used to display the board
void displayBoard(char ticTacToeGame[][3]) {

    // display board
    for (int row = 0; row < 3; row++) {

        cout << endl;

        for (int column = 0; column < 3; column++) {
            cout << "| " << ticTacToeGame[row][column] << " ";
        }

        cout << "|\n";

        if (row < 2) {
            for (int i = 0; i < 19; i++) {
                cout << "-";
            }
        }
    }


} // end of displayBoard()

// function used to get users play
char userPlay() {

    // declaration of variables
    char play;

    cout << "Play: ";
    cin >> play;
    cout << endl;

    return play;

} // end of userPlay()

// function used to add users play to board
char addPlayToBoard(char play, char ticTacToeGame[][3]) {

    for (int row = 0; row < 3; row++) {
        for (int column = 0; column < 3; column++) {
            if (ticTacToeGame[row][column] == play){
                ticTacToeGame[row][column] = 'O';
            }
        }
    }
    return ticTacToeGame;

} // end of addPlayToBoard()

How would I do this?

1 Answers1

2

A good C++ course would cover classes before arrays. The sort of array you're using here is a primitive building block, that's why you are struggling.

We're guessing here a bit in what your course already covered, but this is how you'd normally do it :

class Board {
   char fields[3][3];
public:
   // Class methods
};

Here's the important reason why: C++ classes are full-blown types and can be returned from functions, just like int values. But often that's not even needed: class methods work on the class in-place.

MSalters
  • 173,980
  • 10
  • 155
  • 350