Also any bad things I do in the code, please also mention |
To get the number of people, you read a string in a function (getAmount()), then you decode the string as an integer at lines 23 & 25. Then you handle bad input at lines 48-49 and 53-54. It would be better to centralize all of that code inside getAmount().
First, rather than reading a string and then converting to a number, just read the number directly:
1 2 3
|
int numPeople
std::cout << "How many people are contesting?: ";
cin >> numPeople;
|
Also, you have two places where you need to read a number that is greater than or equal to zero (number of contestants and number of pancakes). So you could make a function handles both cases. The only difference is the prompt so make that a parameter.
When reading and validating input, I find it easiest to break out of the middle of the loop.
Putting this together, getAmount becomes:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
// Prompt for and read an unsigned number.
unsigned getAmount(const char *prompt)
{
unsigned result;
while (true) {
std::cout << prompt;
if (std::cin >> result) {
return result;
} else {
std::cout << "Please enter a number that is zero or more\n";
}
}
}
|
Note that I have not done error recovery when the user enters a bad number. I'll leave that to you if you want to add it.
With this the main program shrinks considerably:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
int main() {
std::cout << "You are holding an eating contest, to see who can eat the mos\
t pancakes!" << std::endl;
int number = getAmount("How many people are contesting?: ");
std::cout << "The number of people contesting: " << number << std::endl << \
std::endl;
std::vector<int> contestants;
for (int i = 0; i < number; i++) {
std::stringstream prompt;
unsigned pancakes;
prompt << "How many pancakes did contestant #" << i << " eat?: ";
pancakes = getAmount(prompt.str().c_str());
contestants.push_back(pancakes);
}
std::cout << "Results:" << std::endl;
for (unsigned x = 0; x < contestants.size(); x++) {
std::cout << "Contestant #" << x
<< " ate " << contestants[x] << " pancakes\n";;
}
std::cin.ignore();
std::cin.get();
return 0;
}
|