Rust reading input from console after printing

Viewed 333

I am just making a little program and I'm trying to get input from the user through the console and this is the code I have:

print!("Enter values seperated by spaces: ");
let mut input = String::new();
match io::stdin().read_line(&mut input) {
    Ok(_n) => println!("{}", input),
    Err(e) => println!("error: {}", e),
}

But instead of printing Enter values seperated by spaces: and then reads the input and prints the input, it reads the input first, and then prints Enter values seperated by spaces: and then it prints the input. How can I make it so that it prints Enter values seperated by spaces: first?

1 Answers

You need to flush your output stream

use std::io::{Write, stdout}

...

print!("Enter values separated by spaces: ");
stdout().flush();

By default, most modern terminals are line-buffered for efficiency. If you want to override this behavior, you have to flush the stream yourself.

Related