I have run this program before and it worked fine. Then I added the "if" statements to the "set" methods and i started seeing very large numbers when I ran the program. What can I do to fix this problem or can someone enlighten me as to why this is happening?
class GradeBook{
public:
void setStudentID(int ID){
if(10000 <= studentID && studentID <= 50000){
studentID = ID;
}
}
int getStudentID(){
return studentID;
}
void setStudentGrade(int grade){
if(0 <= studentGrade && studentGrade <= 100){
studentGrade = grade;
}
}
int getStudentGrade(){
return studentGrade;
}
void displayMessage(){
cout << "Student " << getStudentID() << " has a score of " << getStudentGrade() << endl;
}
private:
int studentGrade;
int studentID;
};
int main(){
int nameOfID;
int nameOfGrade;
GradeBook gb;
cout << "Please enter a student ID: " << endl;
cin >> nameOfID;
gb.setStudentID(nameOfID);
cout << "Please enter the student's grade: " << endl;
cin >> nameOfGrade;
gb.setStudentGrade(nameOfGrade);
getchar();
gb.displayMessage();
getchar();
}
You have your comparisons wrong you meant.
if(10000 >= studentID && studentID <= 50000)
You don't have else statements to make sure the variable is initialized, thus I'd change it to:
if(10000 >= studentID && studentID <= 50000){
studentID = ID;
}
else{
studentID = 0; //or whatever value you want to mean invalid
}
That will hopefully fix your issues.
Two guesses (I'm not that good in C++):
Edit: Actually, forget 2; this seems to suggest that it should work. My C++ is somewhat rusty ;-)
The first thing I noticed is that your ivars are not being initialized so if the input in the setters doesn't validate then the behavior you've identified is to be expected.
You should create a default constructor and initialize the two variables to 0.
when you define GradeBook gb, the private fields (studentGrade and studentID) are not initialized. Then, gb.setStudentID tries to read studentID. studentID would be random value.