2

I'm trying to get user input from the command line in a more visually pleasing way by printing ">> " before reading what the user types in. Then I simply print what was typed in.

use std::io;

fn get_input() -> Result<String, io::Error> {
    print!(">> ");
    let mut result = String::new();
    io::stdin().read_line(&mut result)?;
    Ok(result)
}

fn main() {
    let string = get_input().expect("couldn't read input");
    let string = string.trim();
    println!("== {}", string);
}

When running the above program and typing "test" into the terminal, why is the output of the code snippet this:

test
>> == test

and not this?

>> test
== test
Max Gallup
  • 21
  • 1

1 Answers1

1

Writing to stdout is generally line-buffered, so when using print!() you need to flush() stdout afterwards before reading from stdin.

use std::io::Write;

fn get_input() -> Result<String, io::Error> {
    print!(">> ");

    io::stdout().flush()?;

    let mut result = String::new();
    io::stdin().read_line(&mut result)?;
    Ok(result)
}
vallentin
  • 23,478
  • 6
  • 59
  • 81