问题将字符串添加到字符串

时间:2016-10-27 20:17:20

标签: c++ string insert append token

我正在尝试将令牌放入队列中。但是,当我尝试输入一个具有多个数字(即10,123)的数字时,它将它们作为单独的数字读取。有人能告诉我我做错了什么吗?我已经尝试过字符串插入和附加,但它们似乎都没有工作

queue <string> getTokens(string token){ 

    int a = (int) token.length();
    string temp;
    queue <string> numbers;
    char t;

    for (int i =0; i <a; i++){

        t = token[i];
        while (!isdigit(t)){
        if (t=='+' || t=='-' || t=='/' || t=='*' || t=='^'){
            string temp1;
            temp1 += t;
            numbers.push(temp1);
            temp1.clear();
        }
        else if (t=='(' || t==')'){
            string temp1;
            temp1 += t;
            numbers.push(temp1);
            temp1.clear();
        }

        else if (!isalpha(token[i-1])  && t == 'e' && !isalpha(token[i+1])){
            string e = "2.718";
            numbers.push(e);
        }



        else if (!isalpha(token[i-1]) && t == 'p' && token[i+1]== 'i' && !isalpha(token[i+2])){
            string pi = "3.14169";
            numbers.push(pi);
        }
        break;
    }

        //if it is one single number
        if (!isdigit(token[i-1])  && isdigit(t) && !isdigit(token[i+1])){
            string tt; 
            tt += t;
            numbers.push(tt);
        }


        //if there is more than one number
        else if ((isdigit(t) && isdigit(token[i+1])) || (isdigit(token[i-1])  && isdigit(t))){ //if it is a number              

            string temp2;
            string temp3="k";
            string temp4;
            //cout << t;

            //int j=1;
            if( isdigit(token[i])){
                temp2 += t;

                cout<<"temp2 : "<<temp2<<endl;



                cout <<"temp3 :" << temp3<<endl;
                //temp2.clear();
                temp3 +=temp2;
            }
            temp4.append(temp3);
            temp4 +=temp3;
            //cout<<"hi"<<endl; 


                cout << "This is temp4: " << temp4 <<endl;
                //cout << "this is temp3: " << temp3<< endl;
                //temp2.clear();


            //cout<<temp2 << "yo";
            //temp3.assign(temp2);
            //cout << "temp3 is : "<< temp3;            

        }       

        else 
            continue;
 }


return numbers;

}

int main (){

    string expression;

    getline(cin,expression);
    cout << expression; 
    queue <string> ts;  
    ts= getTokens(expression);
}

1 个答案:

答案 0 :(得分:0)

在每次迭代时,temp2 temp3 temp4变量的值都将被重置 所以它不能保持前一次迭代的值。 我认为这是你可能面临问题的地方。 尝试将其声明为for循环并在获得所需输出后将其清除,以供下次使用

//if there is more than one number
else if ((isdigit(t) && isdigit(token[i+1])) || (isdigit(token[i-1])  && isdigit(t))){ 
//if it is a number              
string temp2;
string temp3="k";
string temp4;

我希望这可能会有所帮助