-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc-eval.cc
More file actions
53 lines (48 loc) · 1.45 KB
/
c-eval.cc
File metadata and controls
53 lines (48 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
* C Expression Evaluator - C example
*
* This program is distributed under the terms of the GPL v3.0 or later
* Download the GNU Public License (GPL) from <https://www.gnu.org>
*
* Copyright(C) 2025, Free Software Foundation, Inc.
* Written by Nicholas Christopoulos <mailto:netnic@proton.me>
*/
#include <cstdio>
#include <cstring>
#include <climits>
#include "cexp.cc"
int main(int argc, char *argv[]) {
char expr[LINE_MAX] = {};
CExp cexp; // the engine
CVar result; // a variable to put the result
// create the expression from arguments
for ( int i = 1; i < argc; i ++ )
if ( strcmp(argv[i], "-d") == 0 ) cexp.verbose = 1;
else strcat(expr, argv[i]);
// if no CLI arguments; read the expression from stdin
if ( strlen(expr) == 0 ) {
while ( fgets(expr, LINE_MAX, stdin) ) {
char *p = expr;
while ( isspace(*p) ) p ++;
if ( strlen(expr) ) { // not empty string
if ( (strcmp(p, "q") == 0) || (strcmp(p, "quit") == 0) // exit command
|| (strcmp(p, "x") == 0) || (strcmp(p, "exit") == 0) )
return 0;
// execute the expression
result.clear();
if ( cexp.evaluate(expr, &result) != E_SUCCESS )
printf("error: (%d) %s\n", cexp.error_code, cexp.error_message.c_str());
else
result.print();
}
}
}
else {
// execute from arguments
if ( cexp.evaluate(expr, &result) != E_SUCCESS )
printf("error: (%d) %s\n", cexp.error_code, cexp.error_message.c_str());
else
result.print();
}
return 0;
}