I have this code:
fn main() {
let mut stdin = io::stdin();
let input = &mut String::new();
loop {
input.clear();
print!("Your age: ");
stdin.read_line(input);
print!("{}", input);
}
}
So when I input something, the programs returns "Your age:" plus my input. But when I run the program I don't want to write the input in a new line. To do something like that in Python, I can write:
var = input("Your age: ")
How can I avoid going to a new line? I'm sure it's simple but I really can't realize how to do that, I tried a lot of different stuff...
You need to flush stdout
before reading the line:
use std::io::{self, Write};
fn main() {
let mut stdin = io::stdin();
let input = &mut String::new();
loop {
input.clear();
print!("Your age: ");
io::stdout().flush();
stdin.read_line(input);
print!("{}", input);
}
}
From the print!
documentation:
Note that stdout is frequently line-buffered by default so it may be necessary to use
io::stdout().flush()
to ensure the output is emitted immediately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With