Skip to content

Commit

Permalink
fix: event-read-char-line double read error & auto enter
Browse files Browse the repository at this point in the history
  • Loading branch information
hthuz committed Dec 11, 2024
1 parent fc8f977 commit e180222
Showing 1 changed file with 27 additions and 14 deletions.
41 changes: 27 additions & 14 deletions examples/event-read-char-line.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@
use std::io;

use crossterm::event::{self, Event, KeyCode, KeyEvent};
use crossterm::{event::{self, Event, KeyCode, KeyEvent, KeyEventKind}, terminal};

pub fn read_char() -> io::Result<char> {
loop {
if let Event::Key(KeyEvent {
code: KeyCode::Char(c),
kind: KeyEventKind::Press,
..
}) = event::read()?
{
Expand All @@ -21,24 +22,36 @@ pub fn read_char() -> io::Result<char> {

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);
loop {
if let Event::Key(KeyEvent{
code,
kind: KeyEventKind::Press,
..
}) = 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());
fn main() -> io::Result<()> {
terminal::enable_raw_mode()?;

println!("read line:\r");
println!("{:?}\r", read_line());
println!("read char:\r");
println!("{:?}\r", read_char());
println!("read char again:\r");
println!("{:?}\r", read_char());

terminal::disable_raw_mode()
}

0 comments on commit e180222

Please sign in to comment.