I just started programming and now I'm working with input validation. I'm running in to a problem where I made a function to validate input but the second iteration of the loop returns the same value as the priming read. Also, this is for school so tips and advice would be more appreciated than complete answers. I don't want to cheat. The code is incomplete but it looks like this:
#include <iostream>
#include <cmath>
using namespace std;
const int VALID_CALORIES = 9;
double validFatGrams(double fatGrams);
double validCalories(double fatGrams, double calories);
int main()
{
double fatGrams = 0, calories = 0, percentCalFromFat = 0;
cout << "Enter the number of fat grams:" << endl;
cin >> fatGrams;
validFatGrams(fatGrams);
fatGrams = validFatGrams(fatGrams);
cout << "Enter the number of calories:" << endl;
cin >> calories;
validCalories(fatGrams, calories);
calories = validCalories(fatGrams, calories);
cout << fatGrams << " " << calories << endl;
}
double validFatGrams(double fatGrams)
{
while(fatGrams < 0)
{
cout << "fat" << " " << fatGrams << endl;
cout << "Invalid input. The number of fat grams must be greater than 0" << endl;
cout << "Enter the number of fat grams (greater than 0):" << endl;
cin >> fatGrams;
}
return fatGrams;
}
double validCalories(double fatGrams, double calories)
{
double passableCalories = 0j;
passableCalories = fatGrams * VALID_CALORIES;
while(calories < passableCalories)
{
cout << "cal" << " " << calories << endl;
cout << "Invalid input. The number of calories must be greater than 0" << endl;
cout << "and must be greater than fat grams x 9." << endl;
cout << "Enter a number of calories greater than " << passableCalories << ":" <<endl;
cin >> calories;
}
return calories;
}
Here's an sample of output:
Enter the number of fat grams:
-1
fat -1
Invalid input. The number of fat grams must be greater than 0
Enter the number of fat grams (greater than 0):
1
fat -1
Invalid input. The number of fat grams must be greater than 0
Enter the number of fat grams (greater than 0):
1
Enter the number of calories:
2
cal 2
Invalid input. The number of calories must be greater than 0
and must be greater than fat grams x 9.
Enter a number of calories greater than 9:
30
cal 2
Invalid input. The number of calories must be greater than 0
and must be greater than fat grams x 9.
Enter a number of calories greater than 9:
30
1 30
Program ended with exit code: 0
Thanks for any advice