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

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

最佳答案

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

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

关于c++ - 无法将数据从txt文件写入对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19593338/

相关文章:

java - 类型转换为更具体的类型

c++ - 包含文件困惑

c# - 以编程方式逐字节复制 CD

c++ - 尝试在 C++ SFML 代码块中设置帧率时出错

c++ - 为什么 "const int"到 "int"的转换有效,但 "const char[]"到 "char *"的转换无效

java - 为什么 Scala 从对象的 main 方法而不是类的静态 main 方法开始?

javascript - 所有对象键减一

c++ - 从 QGraphicsScene 移除 Qpixmap

用于嵌套类的 Javascript css 选择器

Javascript 对象方法不可访问/未定义