2017-10-05 23 views
0

我是C++的新手,我正在为课程制作程序。该计划是两个人之间的井字游戏。我已经完成了一个不使用函数的程序版本,我试图使用它们。C++如何输出一个我在函数中操作的数组?

我想编辑一个函数内的数组,并输出稍后在程序中使用的函数。

这是代码;

// 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() 

我该怎么做?

+2

使用std :: vector或std :: array。 – 2017-10-05 15:09:03

+0

感谢您的回复,将研究如何使用它们。 –

+1

您可能还想了解通过引用传递和传递函数中的值之间的区别。特别是在你的函数addPlayToBoard中 – hellyale

回答

2

一个好的C++课程将涵盖数组之前的类。你在这里使用的这种数组是一个基本的构建块,这就是你挣扎的原因。

我们在这里猜测在你的课程已经覆盖了一点,但是这是你怎么会常做:

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

这里的重要原因:C++类是完全成熟的类型和可以从函数返回,就像int的值。但通常情况下甚至不需要:类方法就地在类上工作。

相关问题