Input, left arrow key - Rust

75 views Asked by At

I wrote this code for create an user input.

std::io::stdout().flush().expect("Failed to flush stdout");
std::io::stdin().read_line(stdin_buffer).expect("Failed to read from stdin");

But when I press the left arrow key:

#> als -ls^[[D^[[D

How do you go backwards in the text?

1

There are 1 answers

0
Manthan Tilva On

As mention in comment of the question, best option is to use third-party crate for this purpose. rustyline may be good option.

Add this crate to your application with.

cargo add rustyline

Below is sample code uisng rustyline.

use rustyline::error::ReadlineError;

fn main() -> rustyline::Result<()> {
    let mut rl = rustyline::DefaultEditor::new()?;
    loop {
        let readline = rl.readline(">> ");
        match readline {
            Ok(line) => {
                let _ = rl.add_history_entry(line.as_str());
                println!("Line: {}", line);
            },
            Err(ReadlineError::Interrupted) => {
                println!("CTRL-C");
                break
            },
            Err(ReadlineError::Eof) => {
                println!("CTRL-D");
                break
            },
            Err(err) => {
                println!("err: {:?}", err);
                break
            }
        }
    }
    Ok(())
}

TL;DR

To implement what you are looking is possible but quite difficult(but doable) and to make that cross platform will be more challenging.

Thing you need to do

You need to read stdin character by character. May be in some OS/terminal you need to add extra code(As it can be buffered).Based on ascii value of character you need to process it.