HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Pi to the Nth Digit

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
nthdigitthe

Problem

I'm trying to teach myself Objective-C/Cocoa for eventual iPhone development but I figured I would start with a terminal app. It takes a user input, strips everything but numerics, then displays PI to the number that is left over.

Could anyone have a quick look over my code and see if there's any optimisations I could make or bad practises I could avoid?

#import 

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        int i;
        char userInput[10];
        printf ("Enter a number: ");

        scanf("%s",userInput);
        NSString * number = [NSString stringWithUTF8String:userInput];

        NSString * strippedNumber = [number stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [number length])];

        i = [strippedNumber intValue];

        printf("%d\n", i);
        if (i == 0) {
            printf("Enter a numeric character\n");
        }
        else {
            printf("%.*f \n", M_PI, i);
        }

    }
    return 0;
}

Solution

BTW: I'm answering from a strong C perspective and weak Objective-C one

To avoid unexpected input and avoid string overflow:

//scanf("%s",userInput);
if (1 != scanf("%9s",userInput)) handle_error();


I'm sure you want:

ref

// printf("%.*f \n", M_PI, i);
printf("%.*f \n", i, M_PI);

Code Snippets

//scanf("%s",userInput);
if (1 != scanf("%9s",userInput)) handle_error();
// printf("%.*f \n", M_PI, i);
printf("%.*f \n", i, M_PI);

Context

StackExchange Code Review Q#36919, answer score: 2

Revisions (0)

No revisions yet.