C令牌化多项式系数 [英] C tokenize polynomial coefficients
问题描述
我试图将来自char数组的多项式的系数放到一个int数组中
我有这个:
char string [] =-4x ^ 0 + x ^ 1 + 4x ^ 3 - 3x ^ 4;
可以用空格将其标记为
-4x ^ 0
x ^ 1
4x ^ 3
3x ^ 4
所以我试图得到:-4,1,4,3成一个int数组
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 ++;
}
但是,我得到一个错误,我无法转换char *
on strncpy(temp [z],p,z);
错误: 'char *'
错误:初始化'char * strncpy(char *,const char *,size_t)'的参数1
$ b b
这是最好的方法是什么?
b
$ b
strncpy(temp [z],p,z);
需要:
strncpy(temp,p,z);
但请记住, strncpy
null-terminate the string。
此外, z
将是系数的长度,
更新:
检查您的链接,我仍然看到几个严重问题:
- 您不能在
strtok
中使用 - 拿起-4x中的一个以及你想要的。 -
strncpy
函数将字符串un-终止,这可能导致atoi
崩溃或随机给出错误的值。一种习惯的形式是手动编写终止符,例如temp [z] ='\0'
。 - 没有得到任何输出值是
系数[a] =
正在写入一些随机存储器,因为a
未初始化。
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?
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.
这篇关于C令牌化多项式系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!