Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

stdout

stdin

rust

The macros println!() and print!() allow you to print strings and variables with and without a trailing newline, respectively. Additionally, the stdin() function provides a function to read a line of user input from STDIN (stdin().read_line(&mut string)).

It should be safe to assume that if the print macro and the read_line function were used consecutively, you should be able to write output and get input on the same line. However, the segments are executed in reverse order when this happens (STDIN is read first, then the statement is printed).

Here is an example of what I am trying to accomplish:

use std::io;

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

The desired output would be (STDIN represents the point where the user is asked for input, it is not actually printed):

Enter a string >> STDIN

The actual output is:

STDIN
Enter a string >> 

On the other hand, the println macro does not reverse the order, although there is still the issue of the trailing newline:

Enter a string >> 
STDIN

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")

I separated the task into the print macro and the read_line function after failing to find a solution in the Rust documentation that would allow something similar to the Python example.

like image 201
computer_geek64 Avatar asked Jan 19 '19 00:01

computer_geek64


2 Answers

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");
}
like image 134
belst Avatar answered Oct 21 '22 06:10

belst


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
like image 21
Stargateur Avatar answered Oct 21 '22 06:10

Stargateur