Here's a simple calculator, knocked-up in a 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;
for (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];
for (int i = 1; i < 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 only for integer maths at the moment, but would be easy to convert for floating point.
- There is no error checking when parsing the number.
- If you want to do multiplication you need to specify
\*
as*
is a symbol to do shell globbing. - You don't need
NSProcessInfo
to get the command line arguments as they are passed tomain()
.