polynomial user-defined constructor

The user-defined constructor takes a char* as argument and uses it to

Page 1 of 1

1 Replies - 3427 Views - Last Post: 16 June 2008 - 07:26 PM Rate Topic: -----

#1 taigern  Icon User is offline

  • New D.I.C Head

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

polynomial user-defined constructor

Post icon  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.

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

//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  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 70
  • View blog
  • 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

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1