2

我目前正在为我的 C++ 课做家庭作业,以制作多人井字游戏,但我在程序的输入部分遇到了问题(我几乎所有其他东西都在运行)。

无论如何,我的目标是提示当前玩家输入格式 row,col 中的一行和一列。然后我需要将他们的标记放在一个代表游戏板的二维数组中。

我认为我可以简单地使用 cin 将他们的输入读入一个 char 数组,然后在该数组中获取 0 位置和 2 位置,然后我会从他们的输入中获得我的两个数字。但是,如果我这样做,我最终会得到输入的 ASCII 值,而不是数字(例如,我得到 49 而不是 '1')。

我觉得我可能忽略了一些非常简单的东西,所以任何输入都会非常有帮助并且非常感谢。这是我所拥有的:

void getEntry(char XorO, char gameBoard[GRID_SIZE][GRID_SIZE])
{
    char entry[3];

    cout << XorO << " - enter row,col: ";
    cin >> entry;

    int row = entry[0];
    int col = entry[2];

    //Then I would use the row, col to pass the XorO value into the gameBoard
}
4

4 回答 4

2

要获得号码,只需执行

row = entry[0] - '0';
col = entry[2] - '0';

这将从 ASCII 转换为实际数字。

于 2013-01-22T19:05:24.417 回答
1

请注意,您正在读入一个char数组。当您将单个chars 转换为ints 时,您将获得字符'0''1'或的 ASCII(或 Unicode)值'2',而不是整数值012。要转换单个数字,您可以使用 ASCII 码的一个有用属性:数字字符是连续的。这意味着您可以'0'从任何数字中提取代码以获得相应的整数值。例如

row = entry[0] - '0';
于 2013-01-22T19:08:20.087 回答
1

让我们operator>>处理解释数字:

void getEntry(char XorO, char gameBoard[GRID_SIZE][GRID_SIZE])
{
    int row, col;
    char comma;

    cout << XorO << " - enter row,col: ";
    std::cin >> row >> comma >> col; 

    if( (!std::cin) || (comma != ',') ) {
      std::cout << "Bogus input\n";
      return;
    }

    //Then I would use the row, col to pass the XorO value into the gameBoard
}
于 2013-01-22T19:10:55.310 回答
0
void getEntry(char XorO, char gameBoard[GRID_SIZE][GRID_SIZE])
{
    char entry[3];

    cout << XorO << " - enter row,col: ";
    cin >> entry;

    int row = entry[0] - '0';
    int col = entry[2] - '0';

    //if grid_size <= 9
}
于 2013-01-22T19:10:15.880 回答