简体   繁体   中英

std::stringstream to return char *

This is my code:

#include <iostream>
#include <sstream>
void serialize(std::ostream& os)
{
   int r1 = 10;
   int r2 = 12;
   os.write(reinterpret_cast<char const*>(&r1), sizeof(r1));
   os.write(reinterpret_cast<char const*>(&r2), sizeof(r2));
}
int main()
{
   std::stringstream ss;
   serialize(ss);
   std::cout<<" Buffer length : " << ss.str().length() <<'\n'; //This print correct length
   const char *ptrToBuff = ss.str().c_str();// HERE is the problem. char * does not contain anything.   
   std::cout <<ptrToBuff; // NOTHING is printed
}

How to get a char pointer to the stream buffer? The problem is std::cout << ptrToBuff; does not print anything std::cout << ptrToBuff; does not print anything

A pointer to the stream will leave a dangling pointer, you can copy the string though:

const std::string s = ss.str(); 

And then point your const char* to it:

const char *ptrToBuff = s.c_str();

In your serialize function you should use << operator to write to ostream:

os << r1 << " " << sizeof(r1) << std::endl;
os << r2 << " " << sizeof(r2) << std::endl;

So the whole code will be: ( see here )

void serialize(std::ostream& os)
{
   int r1 = 10;
   int r2 = 12;
   os << r1 << " " << sizeof(r1) << std::endl;
   os << r2 << " " << sizeof(r2) << std::endl;
}
int main()
{
   std::stringstream ss;
   serialize(ss);  
   std::cout<<"Buffer length : " << ss.str().length() <<'\n';
   const std::string s = ss.str(); 
   const char *ptrToBuff = s.c_str();
   std::cout << ptrToBuff; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM