Reputation: 2062
Hey guys so I'm trying to learn objective c as an independent study for my school and one of my projects just to practice is making a calculator program where the user inputs a string of numbers and operators and the program breaks it apart and does the calculation. Right now I have the input and I'm trying to have it find the operators and put them all in an array so that it can sort them to find order of operations and use the indices to find the different terms; however, when I try to print out the array to see if its holding the chars, it outputs some weird symbols like the apple logo or an upside down question mark. I've made an SSCCE of my problem -- does anyone know whats going on?
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSString *calculation;
char str[50] = {0};
int count = 0;
NSLog(@"What would you like to calculate?");
scanf("%s", str);
calculation = [NSString stringWithUTF8String:str];
for (int i = 0; i < [calculation length]; i++) {
NSRange range = NSMakeRange (i, 1);
if([[calculation substringWithRange: range] isEqualToString: @"*"] ||
[[calculation substringWithRange: range] isEqualToString: @"/"])
count++;
}
char operators[count];
for (int i = 0; i < count; i++) {
for (int j = 0; j < [calculation length]; j++) {
NSRange range = NSMakeRange (j, 1);
NSString *s = [s initWithString:[calculation substringWithRange: range]];
if([s isEqualToString:@"*"]){
operators[i] = '*';
break;
}
if([s isEqualToString:@"/"]){
operators[i] = '/';
break;
}
}
NSLog(@"%c", operators[i]);
}
}
return 0;
}
Upvotes: 2
Views: 5596
Reputation: 27147
To answer your question about what is going on in your code. The "weird symbols" you are seeing are the un-initialized values in memory at your operators[]
array.
To see the reason the char[] is left with garbage values look at this section of your code:
...
NSString *s = [s initWithString:[calculation substringWithRange: range]];
if([s isEqualToString:@"*"]){
operators[i] = '*';
break;
}
...
You are sending initWithString
to s
. s
is not yet allocated. This results in s
being a nil
. And since sending a message like isEqualToString:
to a nil
will essentially evaluate NO
even when an @"*"
is in that range your assignment to operators[i]
will never happen.
Easy fix though, just replace the s
assignment with this:
NSString *s = [calculation substringWithRange:range];
Upvotes: 1
Reputation:
You don't need anything fancy for this. But: use stuff for what it is there for.
#import <Foundation/Foundation.h>
int main()
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
char str[128];
printf("Enter formula:\n");
scanf("%s", str); // this is DAMN unsafe, btw
NSMutableArray *arr = [NSMutableArray array];
char *s = str;
while (*s) {
if (*s == '*') {
[arr addObject:@"*"];
} else if (*s == '/') {
[arr addObject:@"/"];
}
s++;
}
printf("\n");
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"%@", obj);
}];
[pool drain];
return 0;
}
Upvotes: 0