0

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.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
RonthaDon
  • 23
  • 1
  • 1
  • 6
  • Will the board-size be configurable, or always the typical 3x3 of normal Tic-Tac-Toe? If not configurable, you might as well hard-code `'A'` to map to "column" (or "row") `0` and `'B'` to `1` etc. Then do the same mapping for the `'1'` in `"A1"`. – Some programmer dude Feb 05 '17 at 18:56
  • The user can define their board size. (Up to 13x16, min: 3x3) – RonthaDon Feb 05 '17 at 18:58

1 Answers1

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

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

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 2
    It should be noted that for letters this is only valid for encodings where the letters are consecutive (like ASCII). It will fail for e.g. EBCDIC. – Some programmer dude Feb 05 '17 at 19:00
  • @Someprogrammerdude: Oh, I had assumed ASCII or Latin-1 or UTF-8 was somehow a valid assumption in the C++ standard. I stand corrected... – einpoklum Feb 05 '17 at 19:03