如何从 stdin 中读取一个字符而无需按 Enter 键? [英] How can I read one character from stdin without having to hit enter?

查看:62
本文介绍了如何从 stdin 中读取一个字符而无需按 Enter 键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行一个在 stdin 上阻塞的可执行文件,当按下一个键时,立即打印相同的字符,而不必按下 Enter.

I want to run an executable that blocks on stdin and when a key is pressed that same character is printed immediately without Enter having to be pressed.

如何在不按 Enter 的情况下从标准输入读取一个字符?我从这个例子开始:

How can I read one character from stdin without having to hit Enter? I started with this example:

fn main() {
    println!("Type something!");

    let mut line = String::new();
    let input = std::io::stdin().read_line(&mut line).expect("Failed to read line");

    println!("{}", input);
}

我查看了 API 并尝试将 read_line() 替换为 bytes(),但是我尝试的所有操作都需要我在之前按 Enter发生读取.

I looked through the API and tried replacing read_line() with bytes(), but everything I try requires me to hit Enter before read occurs.

这个问题是针对 C/C++ 提出的,但似乎没有标准的方法:无需等待按下回车键即可从标准输入中捕获字符

This question was asked for C/C++, but there seems to be no standard way to do it: Capture characters from standard input without waiting for enter to be pressed

考虑到它在 C/C++ 中并不简单,它在 Rust 中可能不可行.

It might not be doable in Rust considering it's not simple in C/C++.

推荐答案

使用现在可用的ncurses"库之一,例如 这个 一个.

Use one of the 'ncurses' libraries now available, for instance this one.

在 Cargo 中添加依赖

Add the dependency in Cargo

[dependencies]
ncurses = "5.86.0"

并包含在 main.rs 中:

and include in main.rs:

extern crate ncurses;
use ncurses::*; // watch for globs

按照库中的示例初始化 ncurses 并等待单个字符输入,如下所示:

Follow the examples in the library to initialize ncurses and wait for single character input like this:

initscr();
/* Print to the back buffer. */
printw("Hello, world!");

/* Update the screen. */
refresh();

/* Wait for a key press. */
getch();

/* Terminate ncurses. */
endwin();

这篇关于如何从 stdin 中读取一个字符而无需按 Enter 键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆