Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid going to new line with stdin in Rust

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

like image 394
Christopher Loen Avatar asked Sep 14 '25 11:09

Christopher Loen


1 Answers

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.

like image 130
antoyo Avatar answered Sep 16 '25 09:09

antoyo