When I try to parse input from read_line() I get ParseIntError { kind: InvalidDigit }

Viewed 47

I am writing a function that gets an initial length of a vector then reads input until the vector is filled. Things go wrong when I convert the input string into an integer.

fn read_to_vector(prompt: &str) -> Vec<String> {
    println!("Enter the number of inital values: ");
    let length_string:String = read_value();
    let length = length_string.parse::<i32>().unwrap();

    println!("{}", prompt);
    let mut buffer_vector:Vec<String> = Vec::new();

    for _i in 1..(length + 1) {
        let buffer_str:String = read_value();
        buffer_vector.push(buffer_str);
    } 
    return buffer_vector;
}
fn read_value() -> String {
    use std::io;
    let mut buf:String = String::new();
    io::stdin().read_line(&mut buf).expect("Failed to get input");
    return buf;
}

Here is the error message:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', src/main.rs:8:47
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

I searched online but I could not find anything related.

1 Answers

read_line() does not trim any whitespace. There is probably a newline character at the end of the string, which indeed is not a digit, and this causes parsing to fail. To fix this, trim whitespace from the end of the string before returning it:

return buf.trim_end().to_string();

To save an allocation, you can combine trim_end() with truncate() on the owned string:

let new_len = buf.trim_end().len();
buf.truncate(new_len);
return buf;
Related