print! macro not executed until pressing Enter

Viewed 541

I am studying Rust and upon working on the Guessing Game I found this odd behaviour:

use std::io;

fn main() {
    println!("Welcome!");

    let mut input = String::new();
    print!("Please type something:"); // this line is not printed UNTIL the Enter key is pressed
    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read input!");

    println!("Bye!");
}

The following happens:

  1. Welcome! is printed
  2. Please type something: is NOT printed
  3. If you type some text and press Enter, you will see your text followed by Please type something:Bye!

How can I print a message to the standard output and have the input being printed on the same line?

For instance:

Please enter your name:
(user types Chuck Norris)
Please enter your name: Chuck Norris
1 Answers

From the docs for std::print:

Note that stdout is frequently line-buffered by default so it may be necessary to use io::stdout().flush() to ensure the output is emitted immediately.

So looks like you need to call io::stdout().flush().

Related