C 中从变量值查找变量
我正在尝试制作一个类似于国际象棋的游戏。我希望用户输入他们想要移动的棋子的位置,然后他们想要移动它...(在 8x8 网格上 - A1 到 H8)
我无法找到一种简单的方法来查找变量用户输入的内容。我当前拥有的代码是:
void main() {
printf("Enter Piece to Move: ");
scanf("%s",&move);
printf("\n\nWhere would you like to move %s?:",move);
scanf("%s",&to);
[...]
我还有一个包含所有棋子位置的变量列表。我希望发生的是,如果用户输入 A1 以使棋子移动。我想要使用名为 A1 的变量的值。这样我就可以知道这件作品的当前位置以及该地方有什么...
希望这能创造场景并且有人可以提供帮助:)
I am trying to make a game similar to chess. I want the user to type in what position of the piece they want to move is, then were they want to move it... ( on an 8x8 grid - A1 through to H8)
I cant workout a simple way to find a variable from what the user has typed in. The code I currently have is:
void main() {
printf("Enter Piece to Move: ");
scanf("%s",&move);
printf("\n\nWhere would you like to move %s?:",move);
scanf("%s",&to);
[...]
What i also have is a variable list of all the location of pieces. What I would like to happen is, if the user was to enter A1 for the piece to move. I want the value of variable named A1 to be used. This is so I can have the current position of the piece and also what is in the place...
Hope this makes scene and someone can help :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看一下数组的概念。如果您有一个二维数组,您只需将字母“A”转换为数字并将其用作数组中的索引。
Take a look at the concept of arrays. If you have a 2-dimensional array, you just need to convert the letter 'A' to a number and use it as in index in the array.
如果动态获取变量的名称,则无法引用该变量。与 PHP 不同,C 语言无法做到这一点。
您应该手动进行映射
上面几乎是伪代码。我的意思是,你应该注意错误的输入和许多其他事情,但你应该明白这个想法。
You cannot refer to a variable if you dynamically obtain its name. There's just no way to do it in C, unlike, say, PHP.
You should do the mapping manually
The above is almost a pseudocode. I mean, you should take care of bad inputs and many other things, but you should get the idea.
这在 C 中是不可能的。当你的程序运行时,变量的名称不再存在,它们只存在于你的代码中。
相反,您应该使用称为数组的东西。在这里解释起来会花很长时间,我认为你应该读一本关于 C 的书。
That is impossible in C. When your program is running the names of the variables don't exist anymore, they only exist in your code.
Instead you should be using something called an array. It would take far too long to explain here, I think you should read a book on C.
你应该使用你的数据的 2 个“持有者”,一个董事会代表和棋子位置,例如
you should use 2 "holders" of your data, a board representation AND pieces positions like