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

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:

  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.

这篇关于从标准输入中捕获字符而无需等待按下回车键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to enforce move semantics when a vector grows?(当向量增长时如何强制执行移动语义?)
Typedef function pointer?(typedef函数指针?)
Reflection and refraction impossible without recursive ray tracing?(没有递归光线追踪就不可能实现反射和折射?)
Is delete[] equal to delete?(delete[] 是否等于删除?)
Why is unsigned integer overflow defined behavior but signed integer overflow isn#39;t?(为什么定义了无符号整数溢出行为但没有定义有符号整数溢出?)
Unions and type-punning(工会和类型双关语)