views:

127

answers:

4

I'm trying to put the coefficients of polynomials from a char array into an int array
I have this:

char string[] = "-4x^0 + x^1 + 4x^3 - 3x^4";

and can tokenize it by the space into
-4x^0
x^1
4x^3
3x^4

So I am trying to get: -4, 1, 4, 3 into an int array

 int *coefficient;
 coefficient = new int[counter];

 p = strtok(copy, "  +");
 int a;
 while (p)
 {
  int z = 0;
  while (p[z] != 'x')
   z++;
  char temp[z];
  strncpy(temp[z], p, z);
  coefficient[a] = atoi(temp);
  p = strtok(NULL, "  +");
  a++;
 }

However, Im getting an error that I cant convert a char* into a char on strncpy(temp[z], p, z);

error: invalid conversion from ‘char’ to ‘char*’  
error: initializing argument 1 of ‘char* strncpy(char*, const char*, size_t)’

What would be the best way to do this?

A: 

You're passing a char to strncpy:

  strncpy(temp[z], p, z);

The first argument should be a char* pointer, not a single char. What you probably mean to do is:

  strncpy(temp, p, z);
Charles Salvia
+3  A: 

This:

strncpy(temp[z], p, z);

Needs to be:

strncpy(temp, p, z);

But remember that strncpy doesn't always null-terminate the string.

Also, z will be the length of the coefficient, but you need an extra byte in the buffer for the null terminator.

Update:

examining your link, I still see several serious problems:

  • You can't use "-" in strtok because it will pick up the one in "-4x" as well as the ones you want. I think you should split on spaces only and handle the +/- operators as tokens.
  • The strncpy function leaves the string un-terminated, which may cause atoi to crash or give the wrong value randomly. One idiomatic form is to write the terminator manually, e.g., temp[z] = '\0'.
  • The reason you're not getting any output values is that coefficient[a] = is writing to some random memory because a is uninitialized.
Tim Sylvester
Thanks, but for some reason, the values in my coefficient array is all 0http://pastie.org/715627
Raptrex
A: 

The other guys are correct about strncpy()'ing into temp rather than temp[z].

I'm going to suggest that you also want to capture the exponents on your free variable. I observe an implicit "0x^2" term that you appear to be neglecting. If your next step is to evaluate your polynomial for various values of x (or, worse, run a solver on it), you will need to know those powers.

John R. Strohm
A: 

This kind of a solution can be made easily enough but to make it proof against extra white space, missing white space and broad enough to handle multiple operators and variable names this kind of strategy increasingly complex and difficult (Especially if you need to have meaningful error messages if the parse fails).

Seems to me it would be easier to implement a bullet-proof solution using boost.regex (or even boost.spirit if the overall task requires order of operations to be analysed) which can easily handle these kind of syntaxes with a large degree of tolerance.

Elemental