【问题标题】:How to pop all the string from stack and store them in string variable?如何从堆栈中弹出所有字符串并将它们存储在字符串变量中?
【发布时间】:2022-11-06 00:59:56
【问题描述】:
#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;
}

/* 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 Kindly help.*/

【问题讨论】:

    标签: c++


    【解决方案1】:

    你几乎很好,但在while-loop 中你想构建字符串。这可以通过多种方式完成,我推荐的是:

        std::ostringstream oss;
        while (!mudassir.empty()) {
            oss << mudassir.top();
            mudassir.pop();
        }
        std::cout << oss.str() << std::endl;
    

    【讨论】:

    • 是否有理由更喜欢std::ostringstream 而不是普通的std::string
    猜你喜欢
    • 2015-09-09
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 2017-11-16
    • 2015-05-07
    • 2012-04-17
    • 1970-01-01
    • 2014-05-31
    相关资源
    最近更新 更多