How do I print STDOUT and get STDIN on the same line in Rust?

stdout gets flushed on newlines. Since your print! statement does not contain nor end in a newline it will not get flushed. You need to do it manually using std::io::stdout().flush()

For example

use std::io::{self, Write};

fn main() {
    let mut input = String::new();
    print!("Enter a string >> ");
    let _ = io::stdout().flush();
    io::stdin().read_line(&mut input).expect("Error reading from STDIN");
}

you should be able to write output and get input on the same line.

There is no concept of "same line" in stdin and stdout. There are just different stream, if you want to perform terminal manipulation you should use something that handle terminal, like console.

In Python (3.x), this can be accomplished with a single line, because the input function allows for a string argument that precedes the STDIN prompt: variable = input("Output string")

Well, here you go:

use dialoguer::Input;

let name = Input::new().with_prompt("Your name").interact()?;
println!("Name: {}", name);
  • https://docs.rs/dialoguer/0.3.0/dialoguer/struct.Input.html#example-usage

Tags:

Stdin

Stdout

Rust