问题
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?
回答1:
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 causeatoi
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 becausea
is uninitialized.
回答2:
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);
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/1801220/c-tokenize-polynomial-coefficients