How do I take in “A1”-style row+column specificati

2019-09-11 19:35发布

问题:

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.

回答1:

(Assuming the board is 3x3, or at most 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.

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 expresion 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.

... 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 work all the way up to 'Z' of course.