Created
August 2, 2017 14:11
-
-
Save whmountains/acd92a05119be9376f93d540ee563eec to your computer and use it in GitHub Desktop.
CLI Calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io; | |
use std::io::Write; | |
// function to write the prompt | |
fn prompt(message: &str, result: &mut String) { | |
// print the message and flush the buffer | |
print!("{}", message); | |
io::stdout().flush() | |
.expect("Error flushing output"); | |
// read the input into a variable. result is already a mutable pointer so we just pass it along | |
io::stdin().read_line(result) | |
.expect("Error reading input"); | |
// trim whitespace and assign result to a mutable pointer | |
*result = String::from(result.trim()) | |
} | |
fn prompt_number(message: &str, result: &mut f64) { | |
// tmp variable to hold the input string | |
let mut input = String::new(); | |
// passthrough to prompt | |
prompt(message, &mut input); | |
*result = input.parse::<f64>().expect("That's not a number!") | |
} | |
fn main() { | |
loop { | |
// define variables | |
let mut operation = String::new(); | |
let mut num1: f64 = 0.0; | |
let mut num2: f64 = 0.0; | |
prompt("Add, Sub, Mul, Div? ", &mut operation); | |
match operation.to_lowercase().as_ref() { | |
"add" => { | |
// prompt for inputs | |
prompt_number("Number: ", &mut num1); | |
prompt_number("Plus: ", &mut num2); | |
// print the result | |
println!("{} + {} = {}", num1, num2, num1 + num2) | |
}, | |
"sub" => { | |
// prompt for inputs | |
prompt_number("Number: ", &mut num1); | |
prompt_number("Minus: ", &mut num2); | |
// print the result | |
println!("{} - {} = {}", num1, num2, num1 - num2) | |
}, | |
"mul" => { | |
// prompt for inputs | |
prompt_number("Number: ", &mut num1); | |
prompt_number("Times: ", &mut num2); | |
// print the result | |
println!("{} * {} = {}", num1, num2, num1 * num2) | |
}, | |
"div" => { | |
// prompt for inputs | |
prompt_number("Number: ", &mut num1); | |
prompt_number("Divided by : ", &mut num2); | |
// print the result | |
println!("{} / {} = {}", num1, num2, num1 / num2) | |
}, | |
"exit" => { | |
break; | |
} | |
_ => { | |
println!("Invalid Operation!"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment