从标准输入中捕获字符而无需等待按下回车键

2022-01-30 00:00:00 c c++ inputstream

我永远不记得我是如何做到这一点的,因为它对我来说很少出现.但在 C 或 C++ 中,从标准输入读取字符而不等待换行符(按 Enter)的最佳方法是什么.

I can never remember how I do this because it comes up so infrequently for me. But in C or C++, what is the best way to read a character from standard input without waiting for a newline (press enter).

理想情况下,它不会将输入字符回显到屏幕上.我只想在不影响控制台屏幕的情况下捕获击键.

Also ideally it wouldn't echo the input character to the screen. I just want to capture keystrokes with out effecting the console screen.

推荐答案

这在纯 C++ 中无法以可移植的方式实现,因为它过多地依赖于可能与 stdin 连接的终端(它们通常是行缓冲的).但是,您可以为此使用库:

That's not possible in a portable manner in pure C++, because it depends too much on the terminal used that may be connected with stdin (they are usually line buffered). You can, however use a library for that:

  1. conio 可用于 Windows 编译器.使用 _getch() 函数为您提供一个字符,而无需等待 Enter 键.我不是经常使用 Windows 开发人员,但我见过我的同学只是包含 <conio.h> 并使用它.请参阅 Wikipedia 上的 conio.h.它列出了在 Visual C++ 中被声明为弃用的 getch().

  1. conio available with Windows compilers. Use the _getch() function to give you a character without waiting for the Enter key. I'm not a frequent Windows developer, but I've seen my classmates just include <conio.h> and use it. See conio.h at Wikipedia. It lists getch(), which is declared deprecated in Visual C++.

可用于 Linux 的诅咒.兼容的 curses 实现也可用于 Windows.它还有一个 getch() 函数.(尝试 man getch 查看其手册页).请参阅 Wikipedia 上的 Curses.

curses available for Linux. Compatible curses implementations are available for Windows too. It has also a getch() function. (try man getch to view its manpage). See Curses at Wikipedia.

如果您的目标是跨平台兼容性,我建议您使用 curses.也就是说,我确信您可以使用一些函数来关闭行缓冲(我相信这被称为原始模式",而不是熟模式" - 查看 man stty).如果我没记错的话,Curses 会以便携的方式为你处理.

I would recommend you to use curses if you aim for cross platform compatibility. That said, I'm sure there are functions that you can use to switch off line buffering (I believe that's called "raw mode", as opposed to "cooked mode" - look into man stty). Curses would handle that for you in a portable manner, if I'm not mistaken.

相关文章