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?
>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