Extract the coefficients of a polynomial with istringstream c++

自作多情 提交于 2019-12-11 03:08:47

问题


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.

So here's the code:

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

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) {}

Thanks in advance!


回答1:


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; 

at the end of the code block.



来源:https://stackoverflow.com/questions/49495294/extract-the-coefficients-of-a-polynomial-with-istringstream-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!