rpn(1): fixed exiting the program on EOF

This commit is contained in:
Emma Tebibyte 2024-02-01 00:57:51 -07:00
parent 4870f4679c
commit 942e284f93
Signed by: emma
GPG Key ID: 06FA419A1698C270

View File

@ -57,7 +57,7 @@ extern crate sysexits;
use sysexits::EX_DATAERR; use sysexits::EX_DATAERR;
#[derive(Clone, Copy, PartialEq, PartialOrd, Debug)] #[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 { enum CalcType {
Add, Add,
Subtract, 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<CalcType> { fn str_to_calc_type(string: &str) -> Option<CalcType> {
let as_int = string.parse::<f64>(); let as_int = string.parse::<f64>();
let result = match as_int { let result = match as_int {
@ -105,6 +105,12 @@ fn eval(
initial_stack: VecDeque<f64>, initial_stack: VecDeque<f64>,
) -> Result<VecDeque<f64>, EvaluationError> { ) -> Result<VecDeque<f64>, EvaluationError> {
let mut stack = initial_stack; let mut stack = initial_stack;
if input.is_empty() {
stack.clear();
return Ok(stack);
}
// Split the input into tokens. // Split the input into tokens.
let toks = input.split(' ').collect::<Vec<&str>>(); let toks = input.split(' ').collect::<Vec<&str>>();
let mut ops: VecDeque<CalcType> = VecDeque::new(); let mut ops: VecDeque<CalcType> = VecDeque::new();
@ -185,12 +191,15 @@ fn main() -> ExitCode {
if argv.get(1).is_none() { if argv.get(1).is_none() {
while let Ok(_) = stdin().read_line(&mut buf) { while let Ok(_) = stdin().read_line(&mut buf) {
match eval(&buf.trim(), stack) { match eval(&buf.trim(), stack) {
Ok(val) => { Ok(s) => {
stack = val.clone(); stack = s.clone();
let precise = round_precise(
stack.iter().last().unwrap(), let val = match stack.iter().last() {
precision, Some(v) => v,
); None => break,
};
let precise = round_precise(val, precision);
println!("{}", precise.to_string()); println!("{}", precise.to_string());
buf.clear(); buf.clear();
}, },