Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to write a calculation program that, when it has run through once asks the user if they wish to make another calculation. This has the form of a separate function that is called at appropriate points in the main function:

char repeatcalc(char y){

    cout << "Would you like to perform another calculation? [Y]es/[N]o" << endl;
    cin >> y;
    if(y == 'Y' || y == 'y'){
        return y == 'y';
    }
    else if(y == 'N' || y == 'n'){
        return y == 'n';
    }
    else{
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        repeatcalc(y);
    }
}

The idea being, the user hits a button and the function returns either a 'y', an 'n' or repeats itself. This then feed back into a while loop in the main function that repeats if a 'y' is returned and ends if an 'n' is returned.

The repeat section in the function above works in the main code, as does the 'y' return, but when 'n' is selected, it seems to return a 'y' anyway.

I'm missing something obvious, but I can't figure out quite what! Any suggestions?

Thanks.

share|improve this question
Your return statements are off. – chris Feb 1 at 17:10
2  
You are returning a bool.. – Lews Therin Feb 1 at 17:10
1  
return y == 'n' ? – hmjd Feb 1 at 17:11
You never return a value from the last else block. – jrok Feb 1 at 17:12
What was the need to make this recursive ? – AsheeshR Feb 1 at 17:13
show 2 more comments

1 Answer

up vote 0 down vote accepted

Convert your function to return a bool. For example:

 if (y == 'Y' || y == 'y') return true; 
 if (y == 'N' || y == 'n') return false;

...

return repeatcalc() ;

being y a local char variable. This way the function dont need an argument. And you can ask simple if (repeatcalc() ) reapeat;

Also, pay attention: == is for comparing and return a bool, while you are trying to make an assingment: return y='y'; with in this case is just return 'y';

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.