【问题标题】:passing 2d array to the function to change the value将二维数组传递给函数以更改值
【发布时间】:2019-07-24 04:59:49
【问题描述】:

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

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]) 应该从用户那里获取输入并更改网格。它会更改函数中的网格,但不会在函数之外执行任何操作。

【问题讨论】:

  • @Chipster 这可能是重复的,但问题是他已经做对了。
  • 我们经常看到这种情况,新手有一些代码有问题,并且认为他们知道问题出在哪里。但他们往往是错误的。因此,如果您还发布了为什么您认为此代码不会在函数之外更改 grid 可能会有所帮助。在那里你可能犯了错误,因为enter_move 看起来不错。
  • 你试过调试你的程序吗?如果您遇到麻烦,那应该始终是您的首选...
  • 尝试从我们的角度来看待它,到目前为止,您已经发布了一些看起来完全正确的代码,而您所说的只是“它不起作用”。
  • 不应该打印X--\n---\n---\n吗?你在你的while循环中调用make_board——我猜你用这种方式覆盖了以前修改过的板。假设您应该将对该函数的调用移至while(win) 循环之前。

标签: c++ arrays function


【解决方案1】:

问题似乎在这里

   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);
    }

这样您只需设置一次板子。

【讨论】:

  • 这证明问题不在于 OP 认为的问题所在:D
  • 是的,它看起来像一个教科书示例。
  • 我的副本是标题的副本。我讨厌问题不是他们所说的那样。
  • @KatYang 不用担心。这真的没什么大不了的。
猜你喜欢
  • 2020-11-01
相关资源
最近更新 更多