clearing contents of ostringstream object

Discussion in 'C++' started by news.eircom.net, Jul 1, 2005.

  1. Hello,

    How do you clear the contents of an ostringstream object? I've included
    some example code so you can see what I mean.

    t.i.a.
    Craig H.


    #include <iostream>
    #include <string>
    #include <sstream>
    #include <iomanip>

    using namespace std;

    int main(int argc, char* argv[])
    {
    string a("hello");
    string b("world");
    string s1;
    ostringstream oss;

    oss << setiosflags(ios::left) << setfill('O') << setw(10) << a << endl;
    s1 = oss.str();
    cout << s1;

    // how do you clear the ostringstream oss?

    oss << resetiosflags(ios::left) << setfill('W') << setw(10) << b << endl;
    s1 = oss.str();
    cout << s1;

    system("PAUSE");
    return EXIT_SUCCESS;
    }

    /*
    -curent output-
    helloOOOOO
    helloOOOOO
    WWWWWworld

    -desired output-
    helloOOOOO
    WWWWWworld
    */
     
    news.eircom.net, Jul 1, 2005
    #1
    1. Advertisements

  2. news.eircom.net

    Rolf Magnus Guest

     
    Rolf Magnus, Jul 1, 2005
    #2
    1. Advertisements

  3. []
    Do not forget to reset flags. The complete clear is:

    oss.str("");
    oss.clear();
     
    Maxim Yegorushkin, Jul 1, 2005
    #3
  4. From looking at sections 27.7.3.2 and 27.7.1.2 of the standard, it appears
    str("") does not clear the stream bits. It seems to me that in clearing the
    internal buffer, one would intend that the stream bits would also be reset
    (in a good state). Is there a reason this is not the defined behavior?
    Aside from a slight performance hit, I have not been able to think of a
    situation where it would be beneficial to set the internal buffer to an
    empty string (in essence resetting it), but leave the state of the stream
    unchanged. If performance is the reason, then under what conditions will an
    ostringstream enter a "bad" state (needing to be clear()'ed)?

    If I'm just doing stuff like this, is there ever a need to clear():

    // contrived example
    ostringstream oss;
    for (int i = 0; i < 50; ++i)
    {
    oss << "File:" << i;
    cout << oss.str() << endl;
    oss.str("");
    }

    Thanks,
    Kyle
     
    Kyle Kolander, Jul 1, 2005
    #4
  5. []
    Consider:

    #include <iostream>
    #include <sstream>

    int main()
    {
    using namespace std;

    stringstream ss;

    cout << ss.rdstate() << endl;

    ss.str("a");
    int a;
    ss >> a;

    cout << ss.rdstate() << endl;
    }

    outputs:
    0
    4
     
    Maxim Yegorushkin, Jul 4, 2005
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.