After getting the value (cin>> age) you need to check to see if it is your ‘quit’ sentinel value before doing anything else with it.
But...
Sentinel values suck. Don’t use them if you can avoid them.
Many times professors design homework input requirements to use them...
Notice how you are prompting for age in two spots: once before the loop and once in the loop. Notice also how both times you are asking for the next loop. This is a good clue that you should instead ask right at the beginning of the loop, rather than elsewhere.
For dealing with user input, a little helper function is often very useful:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
template <typename T>
bool ask( const std::string& prompt, T& result )
{
std::cout << prompt;
// Attempt to get any input. EOF or blank == user is done giving input
std::string s;
if (!getline( std::cin, s ) or s.empty()) returnfalse;
// Attempt to convert the input to the target object
std::istringstream ss{ s };
ss >> result >> std::ws;
// Returns true if conversion was successful
// and there was nothing else in input besides the requested item
return ss.eof();
}
while (true)
{
if (!ask( "Age of attendee? ", age ) or (age < 0))
// Any invalid input == done
break;
if (!ask( "Item to purchase (1-7)? ", selection ) or (1 > selection) or (selection > 7))
break;
// If we get this far, the user has not failed to input the desired information.
std::cout << "Movie theater snack successfully purchased.\n";
// We can now use the input information to do stuff, like track age and sales statistics...
smallest = std::min( smallest, age );
...
}
// At this point, all user input has been successfully entered.
// Print out your statistics.
std::cout
<< "Age 0 to 18: " << age0_18 << "\n"
<< "Age 19 to 30: " << age19_30 << "\n"
...
<< std::endl;