stringstream: rdbuf()->sgetn(buf, rdbuf()->in_avail()) contentsdiffer from str()

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • whatdoineed2do@yahoo.co.uk

    stringstream: rdbuf()->sgetn(buf, rdbuf()->in_avail()) contentsdiffer from str()

    hi,

    i'm trying avoid uncessary copy of data whilst using the stringstream
    so i am using the sgetn() to copy the data into a buf as apposed to
    getting the same data via the .str() which will construct a string
    object, and a string object copy on return to me.

    however i've noticed that if the last thing put onto the stringstream
    is not txt (an int for example) then the sgetn() using the in_avail()
    DIFFERS from what i get back from .str(). Below illustrates my
    problem

    Am using SunStudio 10 on sparc 5.10 -- haven't had chance to try g++

    any thoughts on where i may be going wrong appreciated
    thanks
    ray


    #include <unistd.h>

    #include <iostream>
    #include <sstream>
    using namespace std;

    int main()
    {
    stringstream s;

    s.seekp(0); s.seekg(0);
    s << "pid=" << getpid();
    cout << "'" << s.str() << "'" << endl; // PID PRINTED AS EXPECTED


    char buf[100];
    memset(buf, 0, 100);

    s.seekp(0); s.seekg(0);
    s << "pid=" << getpid();
    s.rdbuf()->sgetn(buf, s.rdbuf()->in_avail());
    cout << "'" << buf << "'" << endl; // PID NOT PRINTED

    memset(buf, 0, 100);

    s.seekp(0); s.seekg(0);
    s << "pid=" << getpid() << " and some text";
    s.rdbuf()->sgetn(buf, s.rdbuf()->in_avail());
    cout << "'" << buf << "'" << endl; // AS EXPECTED

    return 0;
Working...