Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust: print! doesn't display when trying to get input

So i’m trying to print on the same line because i want the input question to be inline: "enter something: and the input goes here". Similiar to python – input("input: ").
If i try to do it, the print!() that i did doesnt display, it displays after.
I’ve tried flushing the buffer.

print!("enter some thing: ");
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
println!("{}", input);

Above code output will be:

hello
enter some thing: hello

Why does that happen?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The print! adds the text to be printed to a buffer, but doesn’t flush that buffer to output it to the terminal right away, to improve performance when you are printing lots of things.

You said you tried flushing the buffer (as suggested in this question), but perhaps you didn’t flush it at the right place? You need to flush it before reading from stdin. This works for me:

use std::io::Write;

print!("enter some thing: ");
std::io::stdout().flush().unwrap();
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
print!("{}", input);

Example run:

$ ./x
enter some thing: pie
pie
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading