Capture characters from standard input without waiting for enter to be pressed(从标准输入中捕获字符而无需等待按下回车键)
问题描述
我永远不记得我是如何做到这一点的,因为它对我来说很少出现.但在 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:
conio 可用于 Windows 编译器.使用
_getch()
函数为您提供一个字符,而无需等待 Enter 键.我不是经常使用 Windows 开发人员,但我见过我的同学只是包含<conio.h>
并使用它.请参阅 Wikipedia 上的conio.h
.它列出了在 Visual C++ 中被声明为弃用的getch()
.
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. Seeconio.h
at Wikipedia. It listsgetch()
, 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.
这篇关于从标准输入中捕获字符而无需等待按下回车键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从标准输入中捕获字符而无需等待按下回车键
基础教程推荐
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++,'if' 表达式中的变量声明 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01