You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++井字棋playerChoice函数中将用户输入的行列值写入棋盘

方案合理性判断

你想到的直接赋值的方案整体逻辑是合理的,但有两个核心细节需要补充:

  • C++数组下标从0开始计数,而用户输入的行/列范围是1~3,需要先做减1转换再操作数组
  • 必须校验用户选择的位置是否已经落过子(原有值为*才可以落子),避免覆盖已有棋子

正确的playerChoice实现逻辑

你只需要在现有输入校验完成的代码后补充3步即可:

  1. 把用户输入的行、列值各减1,转换为数组可用的下标
  2. 校验目标位置是否为初始的*,如果不是要提示用户重新选择
  3. 直接给数组对应位置赋值为传入的棋子字符(不需要额外条件判断是X还是O,因为形参已经直接传入了当前玩家的棋子)

修改后的完整playerChoice代码

// 建议把形参name改名为playerPiece更符合语义
void playerChoice(char arr[][COLS], char playerPiece) {
  int row, col;

  cout << "What row would you like?\n";
  cout << "Row: ";
  cin >> row;

  while (row < 1 || row > 3) {
    cout << "Error please pick a row in between 1 and 3.\n";
    cout << "Row: ";
    cin >> row;
    cout << endl;
  }

  cout << "What column would you like?\n";
  cout << "Column: ";
  cin >> col;

  while (col < 1 || col > 3) {
    // 原有代码这里错误提示写的是row,已经修正为column
    cout << "Error,please pick a column in between 1 and 3.\n";
    cout << "Column: ";
    cin >> col;
    cout << endl;
  }

  // 转换为数组下标
  int arrRow = row - 1;
  int arrCol = col - 1;

  // 校验位置是否未被占用
  while (arr[arrRow][arrCol] != '*') {
    cout << "This position is already occupied, please choose again.\n";
    // 重新输入行
    cout << "Row: ";
    cin >> row;
    while (row < 1 || row > 3) {
      cout << "Error please pick a row in between 1 and 3.\n";
      cout << "Row: ";
      cin >> row;
    }
    // 重新输入列
    cout << "Column: ";
    cin >> col;
    while (col < 1 || col > 3) {
      cout << "Error,please pick a column in between 1 and 3.\n";
      cout << "Column: ";
      cin >> col;
    }
    // 重新转换下标
    arrRow = row -1;
    arrCol = col -1;
  }

  // 直接落子
  arr[arrRow][arrCol] = playerPiece;
}

现有代码其他可优化点

  • 当前main函数里的循环只跑3轮,最多只能下6个棋子,3*3棋盘总共可以下9个,建议把循环条件改成判断是否还有空位或者是否已经产生赢家
  • main函数里的winner字符串和winner函数重名,会导致编译冲突,建议修改其中一个的命名

内容的提问来源于stack exchange,提问作者MARRSVISTER

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 13:45:08