std :: stringstream返回char *

时间:2020-01-23 16:13:07

标签: c++ stringstream

这是我的代码:

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

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

1 个答案:

答案 0 :(得分:2)

指向流的指针将留下一个悬空的指针,您可以通过以下方式复制字符串:

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