C++ 读取不带逗号的用户输入

C++ Reading in User Input without the commas

本文关键字:用户 输入 读取 C++      更新时间:2023-10-16

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

无论如何,我的目标是提示当前播放器在格式行,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
}

要获得数字,只需

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

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

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

row = entry[0] - '0';

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 inputn";
      return;
    }
    //Then I would use the row, col to pass the XorO value into the gameBoard
}
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
}