Search code examples
utf-8rustnewlinestdiocarriage-return

How to trim off Newline and Carriage-return from a line read from stdin in Rust?


I want to read a line from stdin and store it in a string variable and parse the string value into a u32 integer value. The read_line() method reads 2 extra UTF-8 values which cause the parse method to panic.

Below is what I have tried to trim off Carriage-return and Newline:

use std::io;
use std::str;

fn main() {
    let mut input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(n) => {
            println!("{:?}", input.as_bytes());
            println!("{}", str::from_utf8(&input.as_bytes()[0..n-2]).unwrap());
        }
        Err(e) => {
            println!("{:?}", e);
        }
    }
}

What is the most idiomatic way to do this in Rust?


Solution

  • String has a trim method that returns a trimmed string slice:

    use std::io;
    use std::str;
    
    fn main() {
        let mut input = String::new();
        match io::stdin().read_line(&mut input) {
            Ok(_) => {
                let trimmed_input = input.trim();
                println!("{:?}", trimmed_input.as_bytes());
                println!("{}", trimmed_input);
            }
            Err(e) => {
                println!("{:?}", e);
            }
        }
    }
    

    Result for "test" input:

    [116, 101, 115, 116]
    test