Reputation: 4370
The macro println!
in Rust always leaves a newline character at the end of each output. For example
println!("Enter the number: ");
io::stdin().read_line(&mut num);
gives the output
Enter the number:
56
I don't want the user's input 56
to be on a new line. How do I do this?
Upvotes: 95
Views: 54336
Reputation: 16502
You can use the print!
macro instead.
print!("Enter the number: ");
io::stdin().read_line(&mut num);
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.
Upvotes: 64
Reputation: 1
The '56' is displayed on the next line because the read_line function also reads the newline character \n that the user enters after typing their input. The println! macro then adds another newline character at the end of the output, which causes the value to be displayed on a new line.
To display '56' on the same line, you can use the trim() method to remove the newline character from the end of the input before printing it.
input = input.trim().to_string();
Upvotes: -1
Reputation: 2042
It's trickier than it would seem at first glance. Other answers mention the print!
macro but it's not quite that simple. You'll likely need to flush stdout, as it may not be written to the screen immediately. flush()
is a trait method that is part of std::io::Write
so that needs to be in scope for it to work (this is a pretty easy early mistake).
use std::io;
use std::io::Write; // <--- bring flush() into scope
fn main() {
println!("I'm picking a number between 1 and 100...");
print!("Enter a number: ");
io::stdout().flush().unwrap();
let mut val = String::new();
io::stdin().read_line(&mut val)
.expect("Error getting guess");
println!("You entered {}", val);
}
Upvotes: 157
Reputation: 597
Don't use the print/ln!-macros. Use write/ln!-macros.
It is more verbose, but print/ln! are problematic for using in command-line apps where their output might get piped or redirected to other apps, which is characteristic for Unix environments.
There is used always the same (only once requested and "buffered") stdout-device, but the stdout-device of the system is changed for piping/redirecting. So for each output to stdout you have to request the current stdout-device (std::io::stdout()
). This can be done with write/ln!-macros.
So to say print/ln! is broken and there is an open issue since years.
Upvotes: 1