Pergunta

I'm just starting to teach myself Objective C and have been fooling around with a simple console based calculator. To start I'm asking the user which operation they would like to perform, what two numbers to perform that operation on, and then I print the answer after it's calculated.

That part all seems to work fine - the next piece I'm trying to implement is to allow the user to keep making calculations until they decide they no longer want to. My thinking to approach this was to put the running of the calculator inside a do/while loop at the end of checking to see if the user wants to continue via 'y' or 'no' via scanf();, and then check to see which the user choose to respond with. What I'm encountering though is at the end of the first pass, the request for input via scanf(); just gets ignored and the program terminates.

I was hoping for some help :) I've done my due diligence to the best that I could via troubleshooting, online research(found something on a white space issue with scanf(); however that didn't help), and some guessing however to date I've been unsuccessful. Below is main section of my code:

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


    float answer;
    char op,repeat;
    NSLog(@"Welcome to my sexy calculater, (_(_)!!"); //don't mind me being weird

    Calculater *deskCalc;   
    deskCalc=[[Calculater alloc] init];

    do
    {

        [deskCalc clear];//clear calc

        op =[deskCalc getOperator]; //get +,-,*,or/
        [deskCalc getNumbers]; //get two numbers

        [deskCalc calculate: op];
        answer=[deskCalc accumulater];

        NSLog(@"Your answer is %f!", answer);


        NSLog(@"Would you like to calculate something again(y/n)?");
        scanf("%c",&repeat);
        //NSLog(@"You typed: %c", repeat);

    } while (repeat=='y');

    [deskCalc release];

    [pool drain];
    return 0;
}

Thanks in advance for any help. If I haven't provided enough information I apologize! Please let me know and I'll be more than willing to provide more. Thanks again all!

Foi útil?

Solução

You probably want to have a look at Scanf skips every other while loop in C

You need to do some extra work to ensure that scanf() read the newline that's on stdin after the user enter 'y', 'n', or whatever other streams of keys they hit before pressing enter.

This other posting also seems relevant: Why is scanf() causing infinite loop in this code?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top