std::stringstream 到 return 字符 *

std::stringstream to return char *

这是我的代码:

#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
}

如何获取指向流缓冲区的字符指针? 问题是std::cout << ptrToBuff; does not print anything

指向流的指针将留下悬空指针,但您可以复制字符串:

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

然后将您的 const char* 指向它:

const char *ptrToBuff = s.c_str();

在您的 serialize 函数中,您应该使用 << 运算符写入 ostream:

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

所以整个代码将是:(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; 
}