Trying to make a simple calculator but no matter what I do it always returns 0. The only way it can return 0 is if the match statement doesn't find a possible match for the choice char variable. But that shouldn't be happening because the input always contains a match like 20 + 20 or 10 - 2. Which means that choice somehow isn't being assigned the correct value in the if/else statement. Why?
fn main() {
const DIGITS: &str = "0123456789";
const OPERATORS: &str = "-+*/";
let mut string: String = String::new();
let mut snum1: String = String::new();
let mut snum2: String = String::new();
let mut choice: char = ' ';
let mut has_choice = false;
let mut num1: i32;
let num2: i32;
input!(&mut string);
for i in string.chars(){
for j in DIGITS.chars(){
if i == j && has_choice == false{
snum1.push(i);
}
if i == j && has_choice == true{
snum2.push(i);
}
}
for n in OPERATORS.chars(){
if i == n{
has_choice = true;
choice = i;
}
else{
choice = i;
}
}
}
num1 = snum1.parse::<i32>().unwrap();
num2 = snum2.parse::<i32>().unwrap();
num1 = match choice{
'-' => sub(&num1, &num2),
'+' => add(&num1, &num2),
'*' => mul(&num1, &num2),
'/' => div(&num1, &num2),
_ => 0
};
print!("Your result is {}", num1);
}
fn sub(num1: &i32, num2: &i32) -> i32{
*num1 - *num2
}
fn add(num1: &i32, num2: &i32) -> i32{
*num1 + *num2
}
fn mul(num1: &i32, num2: &i32) -> i32{
*num1 * *num2
}
fn div(num1: &i32, num2: &i32) -> i32{
*num1 / *num2
}
#[macro_export]
macro_rules! input{
($x:expr) => {
std::io::stdin().read_line($x).unwrap();
}
}