Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

So I\'m learning the basics with C++, and I\'ve created a small text based shopp

ID: 658518 • Letter: S

Question

So I'm learning the basics with C++, and I've created a small text based shopping mall which asks the user if they'd like to buy an item. If the user responds with yes, or any variant of yes, it'll list an array of items, from which you can then type in the name of the item you want to buy and it'll say "thanks, you've bought x item, goodbye" and the program will stop. If you decide to put no, it'll say "you have selected no, are you sure you wouldn't like to go back and buy an item". If you put yes, it'll list the array of items again for you to select, however, what i'd like for it to do is to then 'abide' by the previous if statement (as if you were saying yes to the first question).

Hopefully you catch what i'm on about! Thanks.

EDIT: unsure what's so unclear about the question 'what i'd like for it to do is to then 'abide' by the previous if statement (as if you were saying yes to the first question).'

I'm asking if it's possible to go back to a previous if statement that's mentioned earlier on in the code, however, I realise that it's probably not possible and I'm now trying to figure out another way of doing so. Thanks.

Explanation / Answer

That's what the goto statement does, but you should avoid using it (see Go To Statement Considered Harmful). Instead, use a function to combine the original question with its confirmation:

bool confirmBuyAnItem() {
if (answeredYesToPrompt("Would you like to buy an item?"))
return true;

if (answeredYesToPrompt("Are you sure you want to quit?"))
return false;

return true;
}

int main(int argc, char* argv[]) {
while (confirmBuyAnItem())
buyAnItem();

return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote