print! macro not executed until pressing Enter

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

  • 4

    Could be related to not flushing the output buffer?

    – 




  • 2

    @tadman Indeed I can `print!(“Something\n”) but then the \n is printed.

    – 

  • 3

    See the associated issue I linked.

    – 

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().

Leave a Comment