gpt4 book ai didi

c++ - 二进制读/写到 std::stringstream

转载 作者:行者123 更新时间:2023-11-30 02:00:30 39 4
gpt4 key购买 nike

我有以下代码尝试将 unsigned int 和 std::wstring 读/写到 std::stringstream。

#include <memory>
#include <iostream>
#include <vector>
#include <sstream>

class SerializationException : public std::runtime_error
{
public:
SerializationException( const char* msg ) : std::runtime_error( msg ) { }
};

class Serialization
{
public:
static void Write( std::ostream& stream, const std::wstring& item )
{
Write(stream, eStdWString);
Write(stream, item.length());
stream.write( reinterpret_cast< const char* >( item.c_str() ), item.length() );
}

static std::wstring ReadWString( std::istream& stream )
{
const unsigned int type = ReadUInt32(stream);
if ( type != eStdWString )
{
throw SerializationException("Expected eStdWString");
}
const unsigned int length = ReadUInt32(stream);
std::vector< wchar_t > tmpBuf( length );
stream.read( reinterpret_cast< char* > ( tmpBuf.data() ), length );
return std::wstring( tmpBuf.begin(), tmpBuf.end() );
}

static void Write( std::ostream& stream, const unsigned int& item )
{
const unsigned int type = eUInt32;
stream.write( reinterpret_cast< const char* >( &type ), sizeof(type) );
stream.write( reinterpret_cast< const char* >( &item ), sizeof(item) );
}

static unsigned int ReadUInt32( std::istream& stream )
{
const unsigned int type = 0;
stream.read( reinterpret_cast< char* > ( type ), sizeof(type) );
if ( type != eUInt32 )
{
throw SerializationException("Expected eUInt32");
}
const unsigned int tmp = 0;
stream.read( reinterpret_cast< char* > ( tmp ), sizeof(tmp) );
return tmp;
}

private:
enum eTlvBlockTypes
{
eStdWString,
eUInt32
};
};

int main(int, char**)
{
std::wstring myStr = L"HelloWorld!";
int myInt = 0xdeadbeef;

try
{
std::stringstream ss( std::ios_base::out | std::ios_base::in | std::ios_base::binary );
Serialization::Write( ss, myStr );
Serialization::Write( ss, myInt );

myInt = Serialization::ReadUInt32( ss );
myStr = Serialization::ReadWString( ss );
}
catch (const std::runtime_error& ex)
{
std::cout << ex.what() << std::endl;
}
return 0;
}

但是在回读流时我得到一个断言失败,因为流是 NULL,有人可以解释这是为什么,以及如何解决它吗?

编辑:断言失败是 ReadUInt32() 的第 2 行。

stream.read( reinterpret_cast< char* > ( type ), sizeof(type) );

最佳答案

你需要解决这个问题:

stream.read( reinterpret_cast< char* > ( type ), sizeof(type) );

为此:

stream.read( reinterpret_cast< char* > ( &type ), sizeof(type) );

再次说明reinterpret_cast是危险的

关于c++ - 二进制读/写到 std::stringstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15070390/

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