ostringstream and sgetn() weirdness
hi,
i have come aross a strange problem with a bit of code that uses a
ostringstream to build up a string and i extract the string into a
user buf via the sgetn() call instead of via the str() method.
however, it appears that when the contents extracted via sgetn() are
invalid for the first extract.
below is a test prog that demonstrates the issue. we are using Forte
7.0 on solaris 5.8; i dont have access to gcc (or any other c++
compiler). can someone tell me where i'm going wrong?
thanks
ray
#include <strings.h>
#include <iostream>
#include <sstream>
#include <exception>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
try
{
ostringstream dump;
size_t sz = 0;
if (argc == 1) {
dump << "huh?";
sz = dump.tellp();
char tmp[5];
memset(tmp, 0, 5);
dump.rdbuf()->sgetn(tmp, 4);
tmp[4] = NULL;
dump.seekp(0);
// this comes out as empty string!!!
cout << "init str='" << tmp << "'" << endl;
}
const char* what = "abcdefghijklmnopqrstuvwxyz";
dump << what;
sz = dump.tellp();
char* s = new char[sz+1];
memset(s, 0, sz+1);
dump.rdbuf()->sgetn(s, sz);
s[sz] = NULL;
dump.seekp(0);
cout << "inserted string is ok: " << (strcmp(what, s) ==
0 ? "yes" : "no") << endl;
what = "aBcDeFgHiJkLmNoPqRsTuVwXyZ";
dump << what;
sz = dump.tellp();
memset(s, 0, sz+1);
dump.rdbuf()->sgetn(s, sz);
s[sz] = NULL;
cout << "inserted shorter string is ok: " << (strcmp(what,
s) == 0 ? "yes" : "no") << endl;
delete [] s;
}
catch (const exception& ex)
{
cerr << ex.what() << endl;
}
return 0;
}