Hi,
I am writing a student database in C++.
There comes a point in my program where I have a succession of "cout's" requesting the user to input the students grade for a particular course.
I want to check that the input is not less than 0 or greater than 100 (since the grade is a percentage).
I can do this using the following code:
#include <iostream>
using namespace std;
int main(){
double grade(0);
int a(0);
do{
cout<<"Enter students grade: ";
cin>>grade;
if(grade<0 || grade>100){
a = -1;
cout<<"Sorry, the grade you entered was either < 0 or > 100 "<<endl;
}
else break;
}
while(a == -1);
cout<<"Grade = "<<grade<<endl;
return 0;
}
My question is this:
I have been reading up on exception handling using the try, throw and catch keywords and this seems to be a situation where it would be very useful, since in my actual program there are lots of repeats of the above piece of code asking for the grade for lots of courses. My best guess at using try, throw and catch is the following:
#include <iostream>
using namespace std;
int main(){
double grade(0);
try{
cout<<"Enter students grade: ";
cin>>grade;
if(grade<0 || grade>100){
throw -1;
}
else cout<<"Grade = "<<grade<<endl;
}
catch(int a){
cerr<<"Sorry, you entered an incorrect value for 'grade'"<<endl;
}
return 0;
}
This code achieves the requirement of raising an exception if an incorrect grade is entered, however, I cannot see how using try, throw and catch, the user can be given the option to enter the grade again.
Any help would be greatly appreciated
Thanks,
Dave