read_line and print! queue


Hi rusties!
While doing the guessing_game, I’ve bumped into weird behaviour of the program.
I’ve decided to mess around and tweak (which I usually do) the code a little bit:

    // I don't want to put an input in a new line
    print!("Please input your guess: ");

    let mut guess = String::new();

    io::stdin().read_line(&mut guess)
        .expect("Failed to read line");

And it compiled! Here how it ran, notice that it first takes the input and then prints the request text:

     Running `target/debug/guessing_game`
Guess the number!
Please input your guess: You guessed: 42

Now I’m wondering, if it’s ok to do that?


The issue seems to be that stdout is line buffered. You’ll have to add a call to io::stdout().flush() to get the string written. There’s a discussion about changing print! to auto-flush here:


Note that in many other languages you at least have the option of changing the buffering mode of the standard streams, either explicitly in the program or with an environment variable / interpreter flag. At least the former is not possible in Rust (yet):


Thanks! That answers my question. :slight_smile: