added guard for empty expressions

This commit is contained in:
Vera Lewis
2025-12-25 20:25:58 -06:00
parent bc87dc3e88
commit f4528e64b9
2 changed files with 16 additions and 5 deletions

View File

@@ -11,8 +11,13 @@ main (const int argc, const char* argv[])
const char** endPtr = argv+argc, const char** endPtr = argv+argc,
** arg = argv+1 ; ** arg = argv+1 ;
/* Guard for empty expressions */
if (arg>=endPtr) {
error |= ERR_NO_EXPR;
}
char* fmt = "%g\n"; char* fmt = "%g\n";
if (strcmp(*arg,"-f") == 0) { if (!error && strcmp(*arg,"-f") == 0) {
fmt ="%f\n"; fmt ="%f\n";
arg+= 1; arg+= 1;
} }
@@ -35,11 +40,14 @@ main (const int argc, const char* argv[])
} }
/* Detect malformed expressions */
if (!error) {
if (expr == NULL) if (expr == NULL)
error |= ERR_NS_OPERANDS; error |= ERR_NS_OPERANDS;
else if ((*expr).tail != NULL) else if ((*expr).tail != NULL)
error |= ERR_NS_OPERATORS; error |= ERR_NS_OPERATORS;
}
report(&expr, fmt); report(&expr, fmt);
@@ -202,6 +210,8 @@ report(STACK* expr, char* fmt)
else if (error & ERR_DIV_BY_ZERO) else if (error & ERR_DIV_BY_ZERO)
printf("Undefined\n"); printf("Undefined\n");
else if (error & ERR_NO_EXPR)
printf("No expression provided.\n");
else else
printf(fmt, peek(expr)); printf(fmt, peek(expr));
} }

View File

@@ -11,6 +11,7 @@ const int ERR_NS_OPERATORS = 2;
const int ERR_INVALID_INPUT = 4; const int ERR_INVALID_INPUT = 4;
const int ERR_INVALID_FACTORIAL = 8; const int ERR_INVALID_FACTORIAL = 8;
const int ERR_DIV_BY_ZERO = 16; const int ERR_DIV_BY_ZERO = 16;
const int ERR_NO_EXPR = 32;
struct EE_STACK_NODE { struct EE_STACK_NODE {