objective c - Xcode command line tool for calculator -
i want make command line calculator using xcode/osx application/command line tool/foundation
type. in xcode, go products/scheme/edit scheme
. in this, can add or delete command line arguments. these command line arguments stored in argument vector i.e. argv[]
.
i using nsarray
store these arguments in objective-c array.
now, want make calculator can evaluate expression.
for example arguments argv[1]=5
, argv[2]=+
, argv[3]= 10
, argv[4]=-
, argv[5]=2
. so, these arguments evaluate expression , give result. result=13.
#import <foundation/foundation.h> int main(int argc, const char* argv[]) { @autoreleasepool { nsarray *myarray =[[nsprocessinfo processinfo] arguments]; (int i=1; i<argc ; i++) { nslog (@"arguents %d=%@", i, myarray[i]); } return 0; } }
here's simple calculator, knocked-up in few minutes:
#import <foundation/foundation.h> typedef enum { op_none, op_add, op_sub, op_mult, op_div } op; static int calc(nsarray *args) { op op = op_none; int result = 0; (nsstring *arg in args) { if ([arg isequaltostring:@"+"]) { op = op_add; } else if ([arg isequaltostring:@"-"]) { op = op_sub; } else if ([arg isequaltostring:@"*"]) { op = op_mult; } else if ([arg isequaltostring:@"/"]) { op = op_div; } else { int value = [arg intvalue]; // no error checking!!! switch(op) { case op_add: result += value; break; case op_sub: result -= value; break; case op_mult: result *= value; break; case op_div: result /= value; break; case op_none: result = value; break; default: abort(); } op = op_none; } } return result; } int main(int argc, const char **argv) { @autoreleasepool { nsmutablearray *args = [nsmutablearray new]; (int = 1; < argc; i++) [args addobject:@(argv[i])]; nslog(@"result = %d", calc(args)); } return 0; }
compile with:
$ clang -ddebug=1 -g -fobjc-arc -o calc calc.m -framework foundation
tests:
typhon:tinkering (master) $ ./calc 3 + 9 2014-04-26 13:23:05.628 calc[8728:507] result = 12 typhon:tinkering (master) $ ./calc 2 / 1 2014-04-26 13:23:20.500 calc[8738:507] result = 2 typhon:tinkering (master) $ ./calc 99 / 11 2014-04-26 13:23:25.364 calc[8742:507] result = 9 typhon:tinkering (master) $ ./calc 99 / 12 2014-04-26 13:23:27.740 calc[8746:507] result = 8 typhon:tinkering (master) $ ./calc 99 \* 11 2014-04-26 13:23:53.588 calc[8754:507] result = 1089
notes:
- it's integer maths @ moment, easy convert floating point.
- there no error checking when parsing number.
- if want multiplication need specify
\*
*
symbol shell globbing. - you don't need
nsprocessinfo
command line arguments passedmain()
.
Comments
Post a Comment