Skip to content
Snippets Groups Projects
Commit 2f1fcc49 authored by Henrik Tjäder's avatar Henrik Tjäder
Browse files

Extracted input handling into separate function

parent 2e6d5f9c
Branches 2a master
No related tags found
No related merge requests found
extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
let mut tries_counter : u32 = 0;
//println!("The secret number is: {}", secret_number);
loop {
// Get the value from inside the Ok, else print the error
let guess = match get_input() {
Ok(num) => num,
Err(e) => {
println!("{}", e);
continue;
}
};
println!("You guessed: {}", guess);
tries_counter += 1;
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
println!("Total number of attempts: {}", tries_counter);
break;
}
}
println!("Attempts so far: {}\n ", tries_counter);
}
}
fn get_input() -> Result<u32, String> {
let mut text_input = String::new();
println!("Please input your guess.");
/*
Instead of using the expect,
save and return potential error
*/
let input = io::stdin()
.read_line(&mut text_input);
match input {
Ok(_) => (),
Err(e) => return Err(format!("{}", e)),
}
match text_input.trim().parse::<u32>() {
Ok(num) => return Ok(num),
Err(e) => {
return Err(format!("in parsing u32, {}", e));
}
};
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment