pimeson
September 1st, 2004, 11:59 AM
Hello,
I am trying to do the following: write some stuff to a stringstream, output the stringstream to a string, write the string and some stuff into another stringstream; later get the string out of the second stringstream, and resurrect the original stringstream and its content from the string. Here is the example code:
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[]){
int t = 1;
int z;
stringstream stream1;
stringstream stream2;
stringstream stream3;
int size;
string tmp;
char * in;
// write int to first stream
stream1.write(reinterpret_cast<char *>(&t), sizeof(t));
// output stream into string
stream1 >> tmp;
// then string into next stream
size = tmp.size();
stream2.write(reinterpret_cast<char *>(&size), sizeof(size));
stream2.write(tmp.c_str(), size+1);
// get everything out
in = new char[size+1];
stream2.read(reinterpret_cast<char *>(&size), sizeof(size));
stream2.read(in, size+1);
tmp = in;
// and resurect the original stream
stream3 << tmp;
stream3.read(reinterpret_cast<char *>(&z), sizeof(z));
cout << z << "\n";
return 1;
}
The code should output 1 but it outputs -1073745663 so I suppose I've got an over/underflow somewhere or messed up with the number of bytes read. I tried putting just the first stream into a string and resurecting it from there, that worked without problems, so I thought wrapping stringstreams in stringstreams should work too? Any hints?
Thx,
PiMeson
I am trying to do the following: write some stuff to a stringstream, output the stringstream to a string, write the string and some stuff into another stringstream; later get the string out of the second stringstream, and resurrect the original stringstream and its content from the string. Here is the example code:
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[]){
int t = 1;
int z;
stringstream stream1;
stringstream stream2;
stringstream stream3;
int size;
string tmp;
char * in;
// write int to first stream
stream1.write(reinterpret_cast<char *>(&t), sizeof(t));
// output stream into string
stream1 >> tmp;
// then string into next stream
size = tmp.size();
stream2.write(reinterpret_cast<char *>(&size), sizeof(size));
stream2.write(tmp.c_str(), size+1);
// get everything out
in = new char[size+1];
stream2.read(reinterpret_cast<char *>(&size), sizeof(size));
stream2.read(in, size+1);
tmp = in;
// and resurect the original stream
stream3 << tmp;
stream3.read(reinterpret_cast<char *>(&z), sizeof(z));
cout << z << "\n";
return 1;
}
The code should output 1 but it outputs -1073745663 so I suppose I've got an over/underflow somewhere or messed up with the number of bytes read. I tried putting just the first stream into a string and resurecting it from there, that worked without problems, so I thought wrapping stringstreams in stringstreams should work too? Any hints?
Thx,
PiMeson