Home > Software engineering >  How to pop a string from one stack and push onto another?
How to pop a string from one stack and push onto another?

Time:02-19

Code snippet:

string token;

token = mystack.pop();

This gives "operator=" error. It is my understanding this is due to the fact that strings do not have the = operator, and that strcpy() is the proper method.

However, when I use:

strcpy(token, mystack.pop());

I receive "error: ‘strcpy’ is not a member of ‘std’; did you mean ‘strcpy’?".

I am quite confused by this. I am new to C .

My overall goal is to pop, check if it is an operand, then push to the operand stack or the operator stack, if that context helps at all. Thanks

CodePudding user response:

This gives "operator=" error.

Assuming you are using std::stack then its pop() method has a void return type, ie it does not return anything, so you can't assign it to your string. You need to instead read from its top() method before calling pop(), eg:

string token;

token = mystack.top();
mystack.pop();

It is my understanding this is due to the fact that strings do not have the = operator

Then your understanding is wrong, because they do.

and that strcpy() is the proper method.

That is true for C-style char*/char[] strings, but not for C -style std::strings.

CodePudding user response:

The problem is that the member function std::stack::pop has return type of void. You can use std::stack::top before using std::stack::pop as shown below:

    std::string token;
    std::stack<std::string> myStack;
    myStack.push("firstString");
    myStack.push("secondString");
    
    token = myStack.top();
     
    myStack.pop(); 
    

Also, note that std::string has overloaded operator= and that strcpy is used with C-strings which are different from std::string.

CodePudding user response:

pop() only removes the top element from the stack, not return this. You should use

token = mystack.top();
mystack.pop();
  •  Tags:  
  • c
  • Related