Reputation: 45
I found problem on the coding here. I need to read from a text file and then write to an object. However, i cant do it probably. the value in the object seems like it is not initialized.
void readPolynomial(string filename, polynomial& p)
{
//Read in the terms of the polynomial from the data file.
//Terms in the data file are arranged in descending order by the exponent.
//One term per line (coefficient followed by exponent), and there is no blank line.
term temp = term();
double c = 0;
int e = 0;
ifstream fin;
fin.open(filename);
while(!fin.eof())
{
fin >> c >> e;
temp = term(c, e);
p.addTerm(temp);
}
fin.close();
}
here is the header file of the class term.
Default constructor:
term()
{
coef = 0;
exp = 0;
}
term::term(double c, int e)
{
c = coef;
e = exp;
}
Upvotes: 0
Views: 78
Reputation: 96800
Also, you can rewrite your function as:
void readPolynomial(string filename, polynomial& p)
{
double c = 0;
int e = 0;
ifstream fin(filename);
fin.exceptions(std::ios_base::goodbit);
while (fin >> c >> e)
{
term temp(c, e);
p.addTerm(temp);
}
// Exception handling (optional)
try { fin.exceptions(std::ios_base::failbit |
std::ios_base::badbit |
std::ios_base::eofbit );
} catch(...)
{
if (fin.bad()) // loss of integrity of the stream
throw;
if (fin.fail()) // failed to read input
{
fin.clear();
fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
fin.clear();
}
}
Upvotes: 0
Reputation: 28762
It looks like you swapped the parameters and the member variables in the two-parameter constructor. Try:
term::term(double c, int e)
{
coef = c;
exp = e;
}
Upvotes: 3