0

我发现这里的编码有问题。我需要从文本文件中读取,然后写入对象。但是,我可能做不到。对象中的值似乎没有初始化。

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();
}

这是类术语的头文件。

默认构造函数:

term()
{
  coef = 0;
  exp = 0;
}

term::term(double c, int e)
{
  c = coef;
  e = exp;
}
4

2 回答 2

3

看起来您在两参数构造函数中交换了参数和成员变量。尝试:

term::term(double c, int e)
{
  coef = c;
  exp = e;
}
于 2013-10-25T15:06:43.630 回答
0

此外,您可以将函数重写为:

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();
    }
}
于 2013-10-25T15:28:43.487 回答