c++ - 将二维数组传递给函数以更改值

标签 c++ arrays function

编辑: 这是我输入数字时的输出

Please enter the move: 
1
X--
---
---
Please enter the move: 
2
-X-
---
---
Please enter the move: 
3
--X
---
---
Please enter the move: 
4
---
X--
---
Please enter the move: 

更改未保存。

我正在尝试使用用户输入的函数更改数组。它确实获得了输入,但它不会影响函数之外我的数组的任何内容。

我尝试过所有不同的方法

void (char *array[])void(char array[][3])void(char **array)

它们都不起作用。

#include <iostream>
#include <sstream>
#include <fstream>
#include <string.h>
#include <random>

using std::string;
using std::getline;
using namespace ::std;

const string winningCases[8] = {"123","456","789","147","258","369","159","357"};


void make_board(char grid[3][3]){
  // some code which works
}

void print_board(char grid[3][3]){
  // some code which works
}

void enter_move(char grid[][3]){
    char humanMove;
    int num_humanMove;

    while(true){
        cout << "Please enter the move: " << endl;
        cin >> humanMove;

        // find index for a grid
        num_humanMove = static_cast<int>(humanMove) - 49;

        int row = num_humanMove / 3;
        int col = num_humanMove % 3;

        // check right input
        if(49 > static_cast<int>(humanMove) && static_cast<int>(humanMove) < 57){
            cout << "Not valid input. " << endl;

        }else if(grid[row][col] == 'X' || grid[row][col]== 'O'){
            cout << "It's taken. " << endl;

        }else{
            grid[row][col] = 'X';

//            print_board(*grid[3]);

            break;
        }
    }

}

int find_grid_space(char move){
  // some code which works
}

char continue_play(){
  // some code which works
}



int main(int argc, char *argv[]){

    char grid[3][3];


    char play='y';
    bool win=true;
    while(play == 'y' || play == 'Y'){
        while(win){

            make_board(grid);
            print_board(grid);

            enter_move(grid);

            win = !check_for_win(grid);

        }
        play = continue_play();

    }

    return 0;
}

因此,函数 void enter_move(char grid[][3]) 应该从用户那里获取输入并更改网格。它会更改函数中的网格,但不会在函数之外执行任何操作。

最佳答案

问题好像出在这里

   while(win){
        make_board(grid);
        print_board(grid);
        enter_move(grid);
        win = !check_for_win(grid);
    }

每次循环你调用make_board,我猜测每次都会重置板。

你应该有的是这个

   make_board(grid);
   while(win){
        print_board(grid);
        enter_move(grid);
        win = !check_for_win(grid);
    }

这样您只需设置一次电路板。

关于c++ - 将二维数组传递给函数以更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57175547/

相关文章:

c++ - 'WinMain' 的注释不一致

c - 根据 argc 是偶数还是奇数,将 0 添加到 char* 数组

r - 为通过引用替换的 data.tables 编写高效函数

c++ - gcc编译错误 cv.h not found for Opencv

c++ - 与 MySQL 和 C++ 链接

c++ - 为什么编译不会失败?

c++ - 我可以将 std::array 转换为切片吗?或者还有什么我可以用的吗?

c - 声明一个二维字符串数组

javascript - Chrome 扩展函数返回未定义的字符串

c++ - 使用 arrayfire 的未声明标识符