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;
}
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:
You are sending
initWithStringtos.sis not yet allocated. This results insbeing anil. And since sending a message likeisEqualToString:to anilwill essentially evaluateNOeven when an@"*"is in that range your assignment tooperators[i]will never happen.Easy fix though, just replace the
sassignment with this: