How to clear the buffer of a streamstring?

♀尐吖头ヾ 提交于 2019-12-10 15:43:53

问题


I have a streamstring in two loops and it is burning my RAM. So how to clear properly the buffer of a steamstring? It is like that to simplify :

stringstream ss (stringstream::in | stringstream::out);

for()
{
    for()
    {
        val = 2;
        ss << 2;
        mystring = ss.str();
        // my stuff
    }
    // Clear the buffer here
}

It wrote 2 then 22 then 222... I tried .clear() or .flush() but it is not that. So how I do this?


回答1:


The obvious solution is to use a new stringstream each time, e.g.:

for (...) {
    std::stringstream ss;
    for (...) {
        //  ...
    }
}

This is the way stringstream was designed to be used. (Also: do you really want a stringstream, or just an ostringstream?)




回答2:


Set ss.str(""); when you want to clear out the excess characters (Edit: thank you).

Use .clear() if your stream has set any error flags in the process of the prior conversion.




回答3:


If you use C++0x:

ss.swap(stringstream());

Visual Studio 2010 (SP1) supports it.

If you don't use C++0x:

ss.seekp(0);
ss.seekg(0);
ss.str("");
ss.clear();

It won't clear the memory, but you could use your stringstream object as it would be empty before.



来源:https://stackoverflow.com/questions/6370301/how-to-clear-the-buffer-of-a-streamstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!