use std::io::*; fn main() { print!("How many numbers to read? "); stdout().flush().expect("the count of #chars flushed (which we then ignore)."); // Because `print!` doesn't print a \n, and the OS may buffer // stdout waiting for a \n before it bothers printing. // We solve that by calling `flush()`. // (Then, we call `unwrap` to handle any Result::Err, // to keep the compiler from warning us of unhandled Err.) // Read first number let num_inputs = read_int_v2(); // Loop to read remaining numbers for i in 0..num_inputs { print!("Lemme see number #{}: ", i + 1); stdout().flush().unwrap(); let n = read_int_v2(); println!("You gave me {}.", n); } } /* fn read_int_v1() -> u32 { let lines = std::io::stdin().lines(); // an iterator let line = lines.next(); // an Option> let attempted_num = match line { Ok(str) => str.trim().parse::(), Err(msg) => panic!("Failed to read line"), }; // attempted_num is the result of `parse`: a Result // we COULD do another match (and panic); there is also a handy // Result method `unwrap_or`: return attempted_num.unwrap_or(0); //let input: u32 = input.trim().parse().expect("Line didn't contain an unsigned integer"); //input } */ fn read_int_v2() -> u32 { let mut input: String = String::new(); // Create empty string (growable) stdin().read_line(&mut input).expect("a line of input on stdin"); // Store next line of input in String let the_num_read: u32 = input .trim() .parse() .expect("a numeric string"); // also consider: .unwrap_or return the_num_read; }