首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

瓜分字符串 并处理分割后数据

2013-06-26 
分割字符串 并处理分割后数据需要处理过数据之后存入coefficients_[10]中 有x的 x之前是需要存的数据 x之

分割字符串 并处理分割后数据
需要处理过数据之后存入coefficients_[10]中 有x的 x之前是需要存的数据 x之后是在数组中的位置 如果没有x 默认位置为0
输入的字符串为"-12 + 7x2 + 7x9 - 21x5 - 11x7"
要求结果为
term is -12
term is 7x2
term is 7x9
term is 21x5
term is 11x7
Coefficients are: -12,0,7,0,0,-21,0,-11,0,7
问题在于
cur=strcpy(NULL," " );这句之后 发现cur并没有指向下一个数据 反而指向了7x2里的2
求高人指点

int coef= 0;
    int power=0;
int sig;
locale loc;
char *aft;
char *bef;
char* cur; //pointer to the items
    char* po = strdup(up);//copy the string
char* temp;
char* go;

//set coefficients
for(int k = 0; k<10; k++){
coefficients_[k]=0;
}

//cutting the array and output items
cur = strtok(po, " ");
while(cur!= NULL){
if(*cur == '-'){
sig = -1;
cur ++;
}else{
sig = 1;
}
//set the signal for negative item
if(*cur != '+'&& *cur != NULL && *cur != '-'){
cout << "term is " << cur <<endl;
}//end print
               go = strdup(cur);
              temp = strpbrk(go,"x");
              if(temp != NULL){
aft = temp+1;//get the number after x
                        bef = strtok(go,"x");//get the number befor x
coef = atoi(bef);
power = atoi(aft);
coefficients_[power] = coef * sig;
}//end x
     if(isdigit(*go,loc)&&(temp == NULL)){//no x signal
power = 0;
bef = go;
coef = atoi(bef);
coefficients_[power] = coef * sig;
}//end no x
                 


cur = strtok(NULL, " ");
}//end while

}


[解决办法]
如果你是连续拆分一个字符串比如是buf,分隔符split,那么strtok(buf,split)返回第一个,继续strtok(null,split),返回下一个,再继续strtok(null,split),。。。直到返回空。如果中间拆分过其他的字符串,再想继续前一个那是不可能的。比如你先strtok(buf,split),在strtok(buf2,split),然后strtok(null,split),此时返回的是buf2里面的内容。
你的代码中cur = strtok(NULL, " "); 前面调用过strtok(go,"x");所以搜索的源字符串指向go了。

热点排行