How do I take in “A1”-style row+column specifications as input?

Deadly 提交于 2019-12-12 02:14:39

问题


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.



来源:https://stackoverflow.com/questions/42055919/how-do-i-take-in-a1-style-rowcolumn-specifications-as-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!