Language: this article is available in: this article is available in: de

When reading data from the stdin / Terminal you often have to deal with a trailing newline (

→ line feed) in the resulting string. You can get rid of this using the simple .pop() function which removes the last character from the string:

use std::io::{Write, stdin, stdout}; fn main() { // Intro println!("-- INPUT Demo --"); print!("Please enter something: "); stdout().flush().unwrap(); // Input let mut inputvar: String = String::new(); stdin().read_line(&mut inputvar).expect("Error while data input"); inputvar.pop(); // remove trailing newline // Output println!("Eingabe: {}", inputvar); }

I even found a more convenient cross-platform solution which can deal with \r (old Mac) and \r

(Windows):

fn trim_newline(s: &mut String) { if s.ends_with('

') || s.ends_with('\r') { s.pop(); if s.ends_with('\r') { s.pop(); } } }

[Update #1:] There is an even shorter and smarter solution (thanks, Stephan!):

fn trim_newline(s: &mut String) { while s.ends_with('

') || s.ends_with('\r') { s.pop(); } }

[Update #2:] Another good way but without .pop() and using .trim_end_matches() and .truncate() (thanks, thiez!):