从标准输入中捕获字符

从标准输入中捕获字符

本文介绍了从标准输入中捕获字符,无需等待按下 Enter 键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我永远不记得我是如何做到这一点的,因为它对我来说很少出现.但是在 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> 并使用它.请参阅维基百科的 conio.h.它列出了 getch(),它在 Visual C++ 中被声明为已弃用.

  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 查看其手册页).请参阅维基百科的诅咒.

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.

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

08-30 22:47