Max Gallup
Max Gallup

Reputation: 21

Rust read_line() delays stdout buffer until end of scope

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

Upvotes: 2

Views: 661

Answers (1)

vallentin
vallentin

Reputation: 26157

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)
}

Upvotes: 1

Related Questions