Osman Osman - 6 months ago 76
C Question

Objective C parsing hiccup

Please bear with me. I am new to C altogether, let alone Objective C. I am trying to do something that should be simple however its not working. I am scanning a string of numbers that also contains symbols. As the mini function runs through the input string it appends numbers to a new string until it comes across an operator (I'm writing a calculator in my own way as a learning exercise.) Right now I am just doing the beginning part and scanning the string and appending character. Here is my code:

char userInput[99];
NSMutableString *number = nil;
int i;

printf( "Please enter math: " );
scanf( "%s", userInput );
fpurge( stdin );

NSString *InputString = [NSString stringWithUTF8String:userInput];

for (i=0; i < [InputString length]; i++) {
char current = [InputString characterAtIndex:i];
if (isalnum(current)) {
[number appendString:[NSString stringWithCharacters:&current length:1]];
NSLog(@"%@ ", number);

For the life of me I can not seem to figure out why it keeps printing
2012-05-02 19:23:20.935 CALC[1447:403] (null)
instead of the number value for each number it comes across. So for example if there are 5 numbers in the entered string it will print that 5 times.


You never initialized number--so when you call -appendString: on it, you're only appending to nil, and the result is just nil back. Try this for your second line:

NSMutableString *number = [NSMutableString string];

Now number is an empty string object, which is very different from being nil, which is no object at all.