Print!() doesn't execute properly

Here is a piece of code:
// inside main()
// ask for user input
print!("Enter number: ");
let mut str = String::new();
std::io::stdin().read_line(&mut str);
println!("You have entered {str}");
// main function ends right here

output:
4
Enter number: You have entered 4

Question: Why didn't the print! execute immediately?

You need to flush Stdout I guess.

print!("Enter number: ");
std::io::stdout().flush().unwrap();
let mut str = String::new();
std::io::stdin().read_line(&mut str).unwrap();
println!("You have entered {str}");
4 Likes

stdout is line-buffered. println! ends with a newline, so it automatically flushes the buffer to stdout. print! doesn't automatically print a newline, so you must flush the buffer manually, as @Miiao showed.

6 Likes

Thanks everyone.

I also had to add " use std::io::Write; " at the top. Looks like flush() is part of Write and the Write trait had to be brought into the scope too. Thanks.

1 Like

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.