Hi all - hope your weekend is going well.
I've got the following code. It compiles, but gives a warning about a stack overflow error in the istream& operator function. When running the program, it just continuously outputs "Enter ID for student."
What am I missing that makes this recursive? Any suggestions or pointers will be much appreciated!
I hope I got the syntax tags right....
#include<iostream>
#include<string>
using namespace std;
class Student
{
friend ostream& operator<<(ostream&, const Student&);
friend istream& operator>>(istream&, const Student&);
private:
int idNum;
double gpa;
public:
Student(const int = 0, const double = 0.0);
void setIdTo9s();
void setGpaToZero();
};
Student::Student(const int id, const double gp)
{
idNum=id;
gpa = gp;
}
void Student::setIdTo9s()
{
idNum = 9999;
}
void Student::setGpaToZero()
{
gpa = 0;
}
ostream& operator<<(ostream &out, const Student &stu)
{
out<<out<<"Student ID #"<<out<<stu.idNum<<
" gpa is "<<stu.gpa<<endl;
return out;
}
istream& operator>>(istream &in, const Student &stu)
{
const int FOUR_DIGITS = 9999;
const double MAX_GPA = 4.0;
cout<<"Enter ID number for student ";
in>>stu.idNum;
cout<<"Enter gpa ";
in>>stu.gpa;
if(stu.idNum < 0 || stu.idNum > FOUR_DIGITS)
throw("ID number out of range!");
if(stu.gpa > MAX_GPA)
throw(stu.gpa);
return in;
}
int main()
{
const int NUM = 5;
Student stus[NUM];
int x;
for(x = 0; x < NUM; x++)
{
try
{
cin>>stus[NUM];
}
catch(const char *msg)
{
cout<<msg<<endl;
stus[x].setIdTo9s();
stus[x].setGpaToZero();
}
catch(const double grade)
{
cout<<"The gpa "<<grade<<" is too high"<<endl;
stus[x].setIdTo9s();
stus[x].setGpaToZero();
}
}
cout<<endl<<"Student summary:"<<endl;
for(x = 0; x < NUM; x++)
cout<<stus[x]<<endl;
}