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