The second project was due yesterday so I can write about it now. This project had two separate parts, approximating e^x by using the sum 1 + x + x^2/2! + x^3/3! + … + x^n/n!. The second part was a program that determines the number of servings of a type of food needed to maintain a person’s current weight based on calories used in a day. Neither of these are particularly exciting, so I’ll just show off some a little bit of the code.
bool repeat_program()
{
bool valid = false;
do
{
char repeat;
cout << repeat;
if(cin.fail())
{
cin.clear();
cin.ignore(1000, 'n');
valid = false;
}
else if(tolower(repeat) == 'y' )
{
valid = true;
return true;
}
else if(tolower(repeat) == 'n' )
{
valid = true;
return false;
}
else
{
valid = false;
}
}while(!valid);
}
This is pretty much exactly the same code that I used to repeat the program in my last project. Instead of cluttering up the main function, I decided to refactor it into it’s own function. I think that this makes the main function much less ugly and a lot easier to follow. I used this function in both parts of the project and will continue to use it in the future projects.
double get_positive_double(string prompt)
{
double input;
bool valid = false;
do
{
cout input;
if(cin.fail())
{
cin.clear();
cin.ignore(1000, 'n');
valid = false;
cout << "The input must be a number." << endl;
}
else if(input <= 0)
{
cout << "The input must be greater than 0." << endl;
valid = false;
}
else
{
return input;
}
}while(!valid);
}
As I said in my last post, I revamped my input checking code in addition to putting it into it’s own function. Again, this serves to make the main function a lot less ugly and easier to follow. body_weight.cpp e.cpp