From 942e284f9392e6b8ea1d32258081367c757cc157 Mon Sep 17 00:00:00 2001 From: emma Date: Thu, 1 Feb 2024 00:57:51 -0700 Subject: [PATCH] rpn(1): fixed exiting the program on EOF --- src/rpn.rs | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/rpn.rs b/src/rpn.rs index 7e7f948..737325c 100644 --- a/src/rpn.rs +++ b/src/rpn.rs @@ -57,7 +57,7 @@ extern crate sysexits; use sysexits::EX_DATAERR; #[derive(Clone, Copy, PartialEq, PartialOrd, Debug)] -/// enum CalcType is a type containing operations used in the calculator. +// enum CalcType is a type containing operations used in the calculator. enum CalcType { Add, Subtract, @@ -78,7 +78,7 @@ impl fmt::Display for EvaluationError { } } -/// str_to_calc_type converts a string to an optional `CalcType`. +// str_to_calc_type converts a string to an optional `CalcType`. fn str_to_calc_type(string: &str) -> Option { let as_int = string.parse::(); let result = match as_int { @@ -105,6 +105,12 @@ fn eval( initial_stack: VecDeque, ) -> Result, EvaluationError> { let mut stack = initial_stack; + + if input.is_empty() { + stack.clear(); + return Ok(stack); + } + // Split the input into tokens. let toks = input.split(' ').collect::>(); let mut ops: VecDeque = VecDeque::new(); @@ -185,12 +191,15 @@ fn main() -> ExitCode { if argv.get(1).is_none() { while let Ok(_) = stdin().read_line(&mut buf) { match eval(&buf.trim(), stack) { - Ok(val) => { - stack = val.clone(); - let precise = round_precise( - stack.iter().last().unwrap(), - precision, - ); + Ok(s) => { + stack = s.clone(); + + let val = match stack.iter().last() { + Some(v) => v, + None => break, + }; + + let precise = round_precise(val, precision); println!("{}", precise.to_string()); buf.clear(); },