在 C++ 中捕获击键
我一直在做一些阅读,我发现我可以使用 getch() 来获得击键。我所看到的是,这被认为是不好的做法,但我也看到了相互矛盾的意见。我正在为我的班级编写一个控制台应用程序,并且希望能够根据按下的箭头键在屏幕上移动标记(*)。 getch() 是解决这个问题的正确方法吗?或者是否有更好的方法来捕获它。我希望他们能够按下箭头,而不需要按下回车键或其他任何东西。我不需要具体的代码,我只是想知道我是否应该避免使用 getch(),如果是的话,有哪些函数可以实现这种类型的想法。
I have been doing some reading, and I see that I can use getch() to get a keystroke. What I have seen is that this is considered bad practice, however I have seen conflicting opinions. I am writing a console application for my class, and would like to be able to move a marker(*) around the screen based on the arrow keys being pressed. Is getch() the right way to go about this, or is there a better method to capture it. I want them to just be able to push the arrow, not need to push enter or anything. I don't need the code specifically, I just want to know if I should avoid getch(), and if so, what functions are there for this type of idea.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
getch()
不是 C 或 C++ 中的标准函数。它存在于一些过时的编译器中,例如 Turbo C,并且它也在某些常用库中定义,例如作为 curses,但无论如何它是一个 C 函数,而不是 C++。对于 C++,您可能应该坚持使用标准 C++ I/O。如果由于某种原因你不能这样做,那么就选择最便携的选项,例如诅咒。getch()
is not a standard function in either C or C++. It's found in some obsolete compilers, such as Turbo C and it's also defined in certain commonly used libraries such as curses, but in any case it's a C function, not C++. For C++ you should probably just stick with standard C++ I/O. If you can't do this for some reason then go for the most portable option, e.g. curses.您想以非规范模式从终端读取。使用 tcsetattr() 关闭 ICANON 标志。
You want to read from the terminal in non-canonical mode. Use tcsetattr() to turn off the ICANON flag.
如果有效,请使用 getch()。为什么不呢?
Use getch() if it works. Why not?
在 Windows 上,您可以使用 pdcurses:http://pdcurses.sourceforge.net/,它与 ncurses 兼容。
On Windows you can use pdcurses: http://pdcurses.sourceforge.net/, that is compatible with ncurses.