[英]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
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*
指向它:
const char *ptrToBuff = s.c_str();
In your serialize
function you should use <<
operator to write to ostream:在您的
serialize
函数中,您应该使用<<
运算符写入 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.