RE-ENTRY HOMEWORK HELP

So I made most of the code work, it's just I can't get to reentry after a negative gets inputed, it will go onto the next month instead of asking the user to reenter a valid number

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

const int NUMMONTHS = 12;
int NUMYEARS;


int main()
{ char choice;
do{
double inches = 0.0, total = 0.0;

cout << "How many years? ";
cin >> NUMYEARS;
if (NUMYEARS<1)
{
cout << "**** ERROR – INVALID NUMBER OF YEARS – PLEASE TRY AGAIN ***"<<endl;
}

for (int years = 1; years <= NUMYEARS; years++)
{
cout << "Year "<< years<<endl;

for (int months = 1 ; months <= NUMMONTHS; months++)
{
cout << "How many inches of rain for month "<< months<<"? ";
cin >> inches;
if (inches<0)
cout << "**** ERROR – INVALID Amount of rainfall – PLEASE TRY AGAIN ***"<<endl;
total = total+inches;
}
}
cout<<endl;
cout<<fixed<<showpoint<<setprecision(1);
cout <<"Over a period of "<<NUMYEARS*12<<" months, "<<total<<" inches of rain fell."<<endl;
cout <<"Average monthly rainfall for the period is "<<total/(NUMYEARS*12)<<" inches."<<endl;

cout << "Would you like to run this program again? (Y/N)" << endl;
cin >> choice;
}while (choice=='Y'||choice=='y');
}
To validate a negative input, I would use a while loop. For example,

1
2
3
4
5
6
cout << "How many years? ";
cin >> NUMYEARS;
if (NUMYEARS < 1)
{
	cout << "**** ERROR – INVALID NUMBER OF YEARS – PLEASE TRY AGAIN ***" << endl;
}


to

1
2
3
4
5
6
7
8
cout << "How many years? ";
cin >> NUMYEARS;

while (NUMYEARS < 1) // Validate the user input the number 0 or negative.
{
	cout << "**** ERROR – INVALID NUMBER OF YEARS – PLEASE TRY AGAIN ***" << endl;
	cin >> NUMYEARS; // Let the user input the value again here to validate.
}
Topic archived. No new replies allowed.