forked from crossterm-rs/crossterm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent-read-char-line.rs
44 lines (38 loc) · 1003 Bytes
/
event-read-char-line.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//! Demonstrates how to block read characters or a full line.
//! Just note that crossterm is not required to do this and can be done with `io::stdin()`.
//!
//! cargo run --example event-read-char-line
use std::io;
use crossterm::event::{self, Event, KeyCode, KeyEvent};
pub fn read_char() -> io::Result<char> {
loop {
if let Event::Key(KeyEvent {
code: KeyCode::Char(c),
..
}) = event::read()?
{
return Ok(c);
}
}
}
pub fn read_line() -> io::Result<String> {
let mut line = String::new();
while let Event::Key(KeyEvent { code, .. }) = event::read()? {
match code {
KeyCode::Enter => {
break;
}
KeyCode::Char(c) => {
line.push(c);
}
_ => {}
}
}
Ok(line)
}
fn main() {
println!("read line:");
println!("{:?}", read_line());
println!("read char:");
println!("{:?}", read_char());
}