# polynomial user-defined constructor

Page 1 of 1

## 1 Replies - 3427 Views - Last Post: 16 June 2008 - 07:26 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=54969&amp;s=c19a5539f7614b5380b657a2a4e899c1&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 taigern

Reputation: 0
• Posts: 4
• Joined: 04-June 08

# polynomial user-defined constructor

Posted 16 June 2008 - 01:49 PM

The polynomial class stores the objects as an array. I've been working on the constructor for a while. I have debugged it and for some reason, I can't extract the coefficients and subscripts. I was thinking about creating a function that extracts each term from the string and then work with each term, but I'm not sure how to do that.

```private:
int coefficients_[10];

//Prints out the coefficient to the output.
void show(Polynomial* p) {
cout << "Coefficients are: " << p->coefficients_[0];
for (int i=1; i<10; i++) {
cout << "," << p->coefficients_[i];
}
cout << endl;

//Calling the constructor
Polynomial *a;
a = new Polynomial("-12 + 7x2 + 7x9 - 21x5 - 11x7");
show(a);

//User-defined constructor that creates an object with the given string polynomial.
Polynomial::Polynomial( const char *ps){
int i = 0;
int coeff = 0;
int subscript = 0;
char* rest;
char* cCoeff;
char* cScript;
char pString[81];

//copy input arg to temporary string
strcpy(pString, ps);

//get coefficient
cCoeff = strtok(pString, " x");
//convert to int
coeff = atoi(cCoeff);
//get rest of the string, this is where i get stuck. How do i check to see if there's an x in the term??
rest = strpbrk(pString, cCoeff);

//get subscript
cScript = strtok(rest," ");

//convert to int
subscript = atoi(cScript);

//insert in array object
coefficients_[subscript] = coeff;

// i know i need a loop of some sort to get the remainding terms

}
```

Thank you for any hints or tips

Is This A Good Question/Topic? 0

## Replies To: polynomial user-defined constructor

### #2 perfectly.insane

Reputation: 70
• Posts: 644
• Joined: 22-March 08

## Re: polynomial user-defined constructor

Posted 16 June 2008 - 07:26 PM

You're probably going to have to parse that string character by character to get the results that you want.

Is it necessary for you to express the polynomial in string form? If not, then it might be easier to give the coefficients to the constructor directly, perhaps storing them in an array, where x[0] is the coefficient to x^0, x[1] is the coefficient for x^1, etc.

This post has been edited by perfectly.insane: 16 June 2008 - 07:26 PM

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }