【问题标题】:c++ How would I output an an array which I manipulated within a function? [duplicate]c++ 如何输出我在函数中操作的数组? [复制]
【发布时间】:2018-03-17 06:29:20
【问题描述】:

我是 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()

我该怎么做?

【问题讨论】:

  • 使用 std::vector 或 std::array。
  • 感谢您的回复,将研究如何使用它们。
  • 您可能还想了解函数中按引用传递和按值传递之间的区别。特别是在你的函数addPlayToBoard

标签: c++ visual-studio codeblocks


【解决方案1】:

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

我们在这里猜测您的课程已经涵盖的内容,但这是您通常的做法:

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

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

【讨论】:

    猜你喜欢
    • 2020-08-09
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    相关资源
    最近更新 更多