String to int and vector. Help

Hi. this code not work. I try to print an index of the vector, coming from the keyboard.

use std::{fs, io};

fn main() -> io::Result<()> {
let vector = vec!["AAA","BBB","DDD"];

// reading from keyboard
let mut input = String::new();
let stdin_preset = io::stdin();
stdin_preset.read_line(&mut input);
input.trim_end();

println!("{}", vector[input.parse::().unwrap() as usize]); // error :frowning:

}

you should use the "turbofish" operator to annotate the type argument for the parse method, like so:

println!("{}", vector[input.parse::<usize>().unwrap()]);

alternative you, you can use the FromStr trait on the usize type

use std::str::FromStr;
println!("{}", vector[usize::from_str(&input).unwrap()]);

In addition to the problem with type conversion pointed out above, there are two other errors:

  1. You do not return a Result as promised in your type signature. You can fix this by adding Ok(()) to the end of your function.
  2. The result from input.trim_end() is thrown away. You should instead write let input = input.trim_end().

A complete working example with improved error handling could be:

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

fn main() -> io::Result<()> {
    let vector = vec!["AAA", "BBB", "DDD"];

    // reading from keyboard
    let mut input = String::new();
    let stdin_preset = io::stdin();
    match stdin_preset.read_line(&mut input) {
        Ok(_) => {
            let input = input.trim_end();
            match usize::from_str(&input) {
                Ok(index) => {
                    match vector.get(index) {
                        Some(val) => {
                            // success!
                            println!("{}", val)
                        }
                        None => {
                            println!("Invalid index for vector: {}", index)
                        }
                    }
                }
                Err(e) => {
                    println!("Error parsing number from str: {}", e)
                }
            }
        }
        Err(e) => {
            println!("Error reading line: {}", e)
        }
    }
    Ok(())
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.