1

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Ari Rosen
  • 13
  • 1
  • 1
    Does this answer your question? [Why does my string not match when reading user input from stdin?](https://stackoverflow.com/questions/27773313/why-does-my-string-not-match-when-reading-user-input-from-stdin) – Chayim Friedman Jun 23 '22 at 16:30

1 Answers1

0

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;
cdhowie
  • 158,093
  • 24
  • 286
  • 300