Recommended Posts

i wrote a program that takes your age and based of that it tells you what grade you''re in. it''s just to practice my if-then statements. the program works fine, but when i was trying to trap any errors, i realized that the program would crash if the user inputed a consonant instead of a number. how can i prevent this? here''s the code:

//this program asks the user for their age
//and based on that it tells them what grade they''re in
#include <iostream.h>
int main ()
{
int age;
int agree;
cout << "What grade are you in? - By Gomeza54" << endl;
cout << endl;
enter_age: //this is a prompt that asks the user how old they are (duh!)
cout << "Please enter your age: ";
cin >> age;
confirm_age: //this prompt lets the user change the value of the variable age
cout << "Confirm. You are " << age << " years old? (1 - Yes 2- No) ";
cin >> agree;
cin.ignore();
// begin the if statements for the confirmation
if (agree==1) { // if agree is 1 then goto the age calculations
cout << endl;
goto age_calculation;
}
elseif (agree==2) { // if agree is 2 then give
cout << endl; // the user a chance to enter it''s age again
goto enter_age;
}
else { // if agree is not any of the above
cout << "That is an invalid option. Please try again." << endl; // indicate that it is an invalid
goto confirm_age; //entry and return to confirm_age
}
age_calculation: //this is where the age calculation starts
// begin the if statements for the age calculation
// if the age is less 3 or else then print out this and end program
if (age<=3) {
cout << "You are to young to be in school!" << endl;
goto program_end;
}
// if the age is 4 print out junior kindergarden
elseif (age==4) {
cout << "You are in Junior Kindergarden" << endl;
goto program_end;
}
// if the age is 5 print out senior kindergarden
elseif (age==5) {
cout << "You are in Senior Kindergarden" << endl;
goto program_end;
}
// if the age is more than 19 or more then print out this and end program
elseif (age>=19) {
cout << "You are too old to be in school!" << endl;
goto program_end;
}
// if the age can go to school then perform two math equations to figure out grade
else {
cout << "You are in Grade " << (age-6) << " or Grade " << (age-5) << "." << endl;
goto program_end;
}
// when the program is over, run this
program_end:
cout << "Press enter. ";
cin.get ();
return 0;
}

btw - any constructive critism about the program would be very much accepted