c++ - 使用 istringstream c++ 提取多项式的系数

标签 c++ string class polynomials istringstream

目前我正在做一个项目(即创建一个多项式类)并且我已经实现了“加减除等”方法。但是我坚持使用一种方法将 3x^1-2x^4 这样的字符串传递给 0 3 0 0 4 这样的系数 vector 。

代码如下:

  string s;
cin >> s;
istringstream iss(s);
double coeff;
char x, sym;
int degree;
vector<double> coefficients;
int i = 0;
while (iss >> coeff >> x >> sym >> degree) {
    //if (sign == '-') coeff *= -1;
    if (degree == i) {
        cout << coeff << i;
        coefficients.push_back(coeff);
        ++i;
    }
    else {
        for (int j = i; j < degree; ++j) {
            coefficients.push_back(0);
        }
        coefficients.push_back(coeff);
        ++i;
    }
   Polynomial p (coefficients);
   p.write();

顺便说一下,我正在使用 istringstream,但不幸的是,由于某种原因它似乎不起作用而且我无法弄清楚我的代码有什么问题? “多项式 p(系数)”最后似乎是空的。 也许是构造函数的问题?

  Polynomial::Polynomial (const vector<double>& coeff)
  : coeff(coeff)
  {}

  // Constructor from string.
  Polynomial::Polynomial (const string& spoly) : spoly(spoly) {}

提前致谢!

最佳答案

是的,最终我发现了问题所在。我在 Mac 上编译,但当我切换到 Linux 时,它运行完美。因此,Mac 的解决方案是编写

 cout << endl; 

在代码块的末尾。

关于c++ - 使用 istringstream c++ 提取多项式的系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49495294/

相关文章:

c++ - 如何访问超出范围的类?

c++ - 将 boost_numpy3 与 CMAKE 链接起来

c# - 使用 C# 从字符串中提取最后一个单词

python - 覆盖(扩展)默认类?

java - Java 中的接口(interface)、类和构造函数

c++ - wxToggleButton::GetValue() 崩溃

c++ - 使用 VS2012 编译 libffi 失败并出现 fatal error LNK1281 : Unable to generate SAFESEH image

将 C 宏定义字符串连接到文字字符串

java - 使用 String 嵌套 for 循环

c++ - 无需重复代码的继承