使用istringstream c ++提取多项式的系数 [英] Extract the coefficients of a polynomial with istringstream c++

查看:103
本文介绍了使用istringstream c ++提取多项式的系数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在研究一个项目(即创建一个多项式的类),并且已经实现了加减乘除法"方法.但是我仍然坚持从3x ^ 1-2x ^ 4这样的字符串传递到系数为0 3 0 0 4的向量的方法.

currently i'm working on a project (namely, creating a class of a polynomial) and i've already implemented the "add-subtract-divide-and-so-on" methods. But i'm stuck on a method to pass from a string like that 3x^1-2x^4 to a vector of coefficients like 0 3 0 0 4.

所以这是代码:

  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(系数)"为空. 也许与构造函数有关?

By the way, i'm using the istringstream, but unfortunately, for some reason it doesn't seem to work and i can't figure out what's wrong with my code?? The "Polynomial p (coefficients)" seems to be empty at the end. Perhaps it is something with the constructors?

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

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

提前谢谢!

推荐答案

是的,最终我发现了问题所在.我当时在Mac上进行编译,但是当我切换到Linux时,它可以正常工作.因此,适用于Mac的解决方案是编写

Yeah, eventually i found what's wrong. I was compiling on a Mac, but when i switched to Linux it worked flawlessly. So, the solution for Mac would be to write

 cout << endl; 

在代码块的末尾.

这篇关于使用istringstream c ++提取多项式的系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆