This code pop all the required strings from the stack. But i want to store those string elements in a final one string variable. How to do it?
#include <sstream>
#include <stack>
#include <string>
#include<iostream>
using namespace std;
int main()
{
istringstream iss("abdd hhh |post_exp| a * b / (c d) ^ f - g |\\post_exp| anndd jjss");
stack <string> mudassir;
string subs;
while (iss >> subs) {
if (subs == "|post_exp|")
{
while (iss >> subs && subs.find("|\\post_exp|") == string::npos)
{
mudassir.push(subs);
}
}
}
while (!mudassir.empty()) {
mudassir.top();
mudassir.pop();
}
cout << endl;
return 0;
}
CodePudding user response:
Use a while loop
#include <iostream>
#include <stack>
#include <string>
#include <vector>
int main()
{
std::stack<std::string> stack;
stack.push("!");
stack.push("world");
stack.push("hello ");
std::string str;
while (!stack.empty())
{
str.append(stack.top());
stack.pop();
}
std::cout << str;
return 0;
}
CodePudding user response:
You're almost good, but in the while
-loop you'd like to build the string. This can be done multiple ways, what I'd recommend is:
std::ostringstream oss;
while (!mudassir.empty()) {
oss << mudassir.top();
mudassir.pop();
}
// if you'd like it in a variable,
// std::string result = oss.str();
std::cout << oss.str() << std::endl;