Skip to content
Snippets Groups Projects
Select Git revision
  • dd9f8850742c73ad152f1b33a7e181c640f05bd0
  • main default protected
  • update_2024
  • fix_formatting
4 results

io.rs

Blame
  • Forked from orestis.malaspin / rust-101
    118 commits behind the upstream repository.
    orestis.malaspin's avatar
    orestis.malaspin authored and Michaël El Kharroubi committed
    111d3f65
    History
    io.rs 965 B
    use std::io::BufRead;
    
    /// Reads i32 from the command line and returns a [Vec] containing
    /// these numbers. Returns errors when the parsing fails.
    pub fn read_command_line() -> Result<Vec<i32>, String> {
        let mut v = Vec::new();
        let stdin = std::io::stdin();
        println!("Enter a list of numbers, one per line. End with Ctrl-D (Linux) or Ctrl-Z (Windows).");
    
        for line in stdin.lock().lines() {
            let line = match line {
                Ok(l) => l,
                Err(_) => {
                    return Err(String::from("Could not read line"));
                }
            };
    
            match line.trim().parse::<i32>() {
                Ok(num) => v.push(num),
                Err(_) => {
                    return Err(String::from("Could not parse integer"));
                }
            }
        }
        Ok(v)
    }
    
    /// Prints all the elements of the `tab`.
    /// Tab is borrowed here
    pub fn print_tab(tab: &Vec<i32>) {
        for t in tab {
            print!("{} ", t);
        }
        println!();
    }