By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,264 Members | 1,237 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,264 IT Pros & Developers. It's quick & easy.

istringstream behavior

P: 2
Since the strstream classes will be deprecated in the future, I have been looking for an alternative to this class for performing binary I/O. stringstream indicates that you can use rdbuf()->pubsetbuf(buf,size) to set the internal streambuf to point to your binary data and then allow you to perform normal stream read/writes. The example below works with GNU but doesn't work with Visual C++ or Sun studio. The old istrstream way works fine but can't seem to get istringstream to work the same way. If this isn't the way to perform binary I/O, I'm looking for alternatives. The only way I was able to get this example to work was to create a stringstream open for input/output, write the buffer with a write command and then read back with my read method.

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

typedef struct {
float f;
int i;
double d;
void print( std::ostream& o ) const {
o<<"f="<<f<<" i="<<i<<" d="<<d<<std::endl;
void read( std::istream& in ) {
// assumes everything is aligned properly for example purposes*)&f, sizeof(float));
if (!in.good()) std::cout<<"read failed: f\n";*)&i, sizeof(int));
if (!in.good()) std::cout<<"read failed: i\n";*)&d, sizeof(double));
if (!in.good()) std::cout<<"read failed: d\n";
void write( std::ostream& os ) {
os.write((char*)&f, sizeof(float));
if (!os.good()) std::cout<<"write failed: f\n";
os.write((char*)&i, sizeof(int));
if (!os.good()) std::cout<<"write failed: i\n";
os.write((char*)&d, sizeof(double));
if (!os.good()) std::cout<<"write failed: d\n";
} str_t;

main() {

using namespace std;
str_t sti, sto;
istringstream s(ios::binary);
cout<<"in_avail: " << s.rdbuf()->in_avail()<<endl;
s.rdbuf()->pubsetbuf( (char*)&sti, sizeof(str_t));
cout<<"in_avail: " << s.rdbuf()->in_avail()<<endl;
if (!s.good()) cout << "string buffer error\n"; s );
if (!s.good()) cout << "string buffer error after read\n";
return 0;
Sep 21 '06 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.