Search code examples
c++stringclasspolynomialsistringstream

Extract the coefficients of a polynomial with istringstream c++


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!


Solution

  • 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.