gpt4 book ai didi

c++ - std::stringstream返回char *

转载 作者:行者123 更新时间:2023-12-02 10:06:44 24 4
gpt4 key购买 nike

这是我的代码:

#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

最佳答案

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

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

关于c++ - std::stringstream返回char *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59882828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com