C++ 读取不带逗号的用户输入
C++ Reading in User Input without the commas
我目前正在为我的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)值,而不是整数值0
、1
或2
。要转换单个数字,可以使用 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
}
相关文章:
- C++如何通过用户输入删除列表元素
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 在C++中,我如何接受不同于同一行的用户输入
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 显示基于用户输入的整数的字符
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 打印时有二叉树问题.用户输入不打印任何内容
- C ++奇怪的数组由用户输入
- 如何允许大写和小写用户输入?
- C++读取用户输入而不按回车键(Mac OS X),与Turbo Pascal中的读取键相同
- 如何存储用户输入的所有数据,然后在他们想要查看所有数据时显示它们
- 如何使用用户输入变量制作二维数组?
- 用户输入字符串的文件附加问题..C++
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 如何使用递归循环我的代码(当用户输入无效输入时,它会再次提示他们)?