帕斯卡的 readkey 是否有等效项?在 C 或 C++ 中?
我正在寻找一个等待用户按键的控制台功能。我希望它像帕斯卡的readkey一样;就像在仅限控制台的解决方案中一样。没有 GUI 库/图形库/窗口库/WinApi 调用 (Windows)。它应该是跨平台的并且(最好)是 C std 库或 C++ 类库的一部分。那么有没有这样的函数/类方法等?
I am looking for a Console function that waits for the user to press a key. I want it to be like Pascal's readkey; as in a Console Only solution. No GUI library / Graphics Library / Windowing Library / WinApi Calls (Windows). It should be cross-platform and (preferably) part of the C std library or C++ Class Library. So is there any such function / class method etc. ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C 标准库没有“键盘缓冲区”的概念。输入/输出主要是基于行的(按下 ENTER 时触发)。
您有几个选择:
setvbuf()
并使用fgetc()
(如果您没有更改缓冲策略,请等待 ENTER)The C Standard library has no notion of a "keyboard buffer". input/output is mostly line-based (triggered when ENTER is pressed).
You have a few options:
setvbuf()
and usefgetc()
(and wait for ENTER if you didn't change the buffering strategy)据我所知,您的产品没有便携式解决方案。在 Windows 中,您可以使用标头
,其中有一个名为getch()
的函数,用于直接从控制台获取字符。如果您使用的是 Linux,则可以使用库 ncurses。As far as I know there is no portable solution for your item. In windows, you can use the header
<conio.h>
which has a function calledgetch()
for getting a char directly from the console. If you are in Linux, then you can use the library ncurses.如果您处于 Windws 运行时环境中,则可以使用非标准 C 函数 kbhit( )。 Linux 上有一个与 Windows 等效的 C 语言
kbhit( )
。该函数正是您想要的:它会告诉您是否已键入键盘字符,而无需读取该字符;或者,如果已输入一个字符,则将读取并向您发送一个字符。您可以在这里找到它:http://pwilson.net/sample.html
向下滚动到该段落标题为“Linux 和 Unix 的单字符键盘输入”
HTH
If you're in a Windws run-time environment, you can use the non-standard C function kbhit( ). And there's a C-language Linux equivalent for Windows
kbhit( )
. The function does just what you want: it will tell you if a keyboard character has been typed without reading the character; or, alternatively, will read and deliver to you one character iff one has been typed. You can find it over here:http://pwilson.net/sample.html
Scroll down to the paragraph headed "Single-character keyboard input for Linux and Unix"
HTH
考虑过 _getch 吗?
Considered _getch ?
简单:
字面上相当于 C# 中的
readkey()
。Simple:
Literally the equivalent for
readkey()
in C#.