0

Hi

part of a homework .
I got a lek in this code when using string for parsing
I do not 'have' to use string.. it just seemed comfortable
input is of the form 2*x**6+term+term+...
[ full source code availabe if that helps ]

#include <string>

//possibly causes memleak - try switching to c string
Polynomial::Polynomial(char* poly):_head(NULL){
	string s = poly;
	s = "+" + s;

	double cof;
	int exp;
	int chars;

	unsigned int index = 0;
	while (index != string::npos){
		s = s.substr(index+1);
		chars = sscanf(s.c_str(),"%lf *x** %d",&cof,&exp);
		if (chars == 2){
			insert(cof,exp);
		} else {
			cout<<"Wrong Format!";
			break;
		}
		index = s.find_first_of("+",index);
	}
}
2
Contributors
1
Reply
2
Views
12 Years
Discussion Span
Last Post by jwenting
0

you do seem to do a lot of string manipulation which may not be necessary at all.

string s = poly;
s = "+" + s;

would be more efficiently written as

string s = "+" + poly;

for example.

while (index != string::npos)
{
   s = s.substr(index+1);
   chars = sscanf(s.c_str(),"%lf *x** %d",&cof,&exp);

are you sure you want to do this?
My guess is you intend to do something along the lines of

while (index != string::npos)
{
    chars = sscanf(s.substr(index+1).c_str(),"%lf *x** %d",&cof,&exp);

P.S. Use C++ style braces and indentation.
Also use code tags when posting code...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.