无法将数据从txt文件写入对象

时间:2013-10-25 15:02:05

标签: c++ class object file-io filestream

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

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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分: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();
    }
}