Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print output without a trailing newline in Rust?

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?

like image 585
7_R3X Avatar asked May 30 '16 18:05

7_R3X


People also ask

How do you print a new line in rust?

Macro std::println Prints to the standard output, with a newline. On all platforms, the newline is the LINE FEED character ( \n / U+000A ) alone (no additional CARRIAGE RETURN ( \r / U+000D )).

How do you flush stdout in Rust?

Macro std::print 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. Use print! only for the primary output of your program.


2 Answers

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 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); } 
like image 110
Induane Avatar answered Oct 04 '22 00:10

Induane


You can use the print! macro instead.

print!("Enter the number : "); io::stdin().read_line(&mut num); 

Beware:

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 40
sjagr Avatar answered Oct 04 '22 00:10

sjagr