4

I'm trying to print on the same line because I want the input question to be inline like 'enter something: input goes here'. Similiar to python's input("input: "). If I try to do it, the print! text doesnt display, it displays after I've pressed enter. 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?

0

1 Answer 1

10

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.