Issue with print! sequencing

Hi Community,
I have started with the hello world and looking some help with this number guessing game.
I need to print asking for a number from user, but print! comes post read_line , however when I use println instead it prints and then read_line.

can you suggest what can be done here, so sequence would always preserve and I get cursor after the print


use std::io;

fn main() {
    let string = read("Please enter the number: ");
    println!("you guessed {}", string);
}


fn read(message : &str) -> String {
    if message != "" {print!("{}", message )} // <-- replacing print with println works, 
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read line");
    input
}

The print!() macro doesn't flush standard out to the terminal (it only flushes on newlines) so you'll need to do it yourself.

Normally I'd use std::io::stdout() and write!() directly to that.

use std::io::{self, Write, Read};

fn main() -> Result<(), io::Error> {
  let mut stdout = io::stdout();
  let mut stdin = io::stdin();

  write!(stdout, "Please enter the number: ")?;
  stdout.flush()?;

  let mut input = String::new();
  stdin.read_line(&mut input)?;

  println!("Your input: {}", input);

  Ok(())
}
1 Like

Ok I found some solution online.. adding below line works.

io::Write::flush(&mut io::stdout()).expect("flush failed!");
//or 
io::Stdout::flush(&mut io::stdout()).expect("flush failed!");

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.