2

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!

alienflow
  • 400
  • 7
  • 19
  • 3
    It sounds like you may need to learn how to use a debugger to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming. Further reading: [How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – NathanOliver Mar 26 '18 at 15:40
  • 1
    Also, Why are you extracting `sign` at the end of the term? That means you need a last term like `2x^3-` for it to be successful. – NathanOliver Mar 26 '18 at 15:41
  • It is not about whether i want to do any programming or not, here i have got a question, if anybody could help me find what is wrong i would really appreciate, if you cannot, better do not write anything then – alienflow Mar 27 '18 at 08:25
  • Does your strings contain any space? Like in `3x^1 -2x^4` or `3x^1 - 2x^4`. Otherwise you should first check if the extraction works in isolation: https://ideone.com/OgHFOF – Bob__ Mar 27 '18 at 09:09
  • @Bob__ that's definitely something really strange, even the improved code that you've posted doesn't work for me, because i can't enter the loop. But, many thnxx anyway – alienflow Mar 27 '18 at 09:33

1 Answers1

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.

alienflow
  • 400
  • 7
  • 19