开发者

ObjC: scanf skipped in do/while loop

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 fo开发者_如何转开发r 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!


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜