如何接收"A1"样式的行+列规范作为输入? [英] How do I take in "A1"-style row+column specifications as input?
问题描述
我正在用C ++编写一个TicTacToe游戏.我正在使用2D角色数组将每个玩家的棋子输入一个正方形.但是,对于输入,我要求用户输入A1,它将是board [0] [0]和游戏板的左上角.如何允许用户输入A1,但仍然允许它不使用硬编码就成为board [0] [0]?另外,用户可以确定板子的尺寸.最小:3x3,最大:13x16.
I am writing a TicTacToe game in C++. I am using a 2D character array to input each player's piece into a square. However, for input I am asking the user to type in A1, which will be board[0][0] and the top left corner of the game board. How do I allow the user to type in A1 but still allow that to be board[0][0] without hard coding? Also, the user can determine the board size. Min: 3x3, max: 13x16.
推荐答案
(假设板子是3x3,或最多9x9)
从用户那里获得两个字符,确保第一个是大写字母,第二个是数字,并且它们在正确的范围内.
Get two characters from the user, ensure the first is an uppercase letter and the second is a digit, and that they're in the right range.
请注意-在大多数平台上,您可能正在使用-如果字符变量c
的值为'A'
,'B'
或'C'
,则表达式c - 'A'
的值为0
,1
或2
,您可以将其用作索引.但是,正如@SomeProgrammerDude指出的那样,它不是100%可移植的代码.
Note that - on most platforms you are likely to be working on - if the character variable c
has value 'A'
, 'B'
or 'C'
then the expression c - 'A'
has value 0
, 1
or 2
, which you can use as an index. It's not 100% portable code, though, as @SomeProgrammerDude notes.
...如果板子较大,则可能必须允许列和行的多字符规范,并对其进行适当的解析.当然,c - 'A'
索引最多只能使用'Z'
.
... if the board is larger you may have to allow for multiple-character specification of column and row, and parse them appropriately. The c - 'A'
indexing will only work up to 'Z'
of course.
这篇关于如何接收"A1"样式的行+列规范作为输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!