[ENet-discuss] ENetPacket to std::string

Thorbjørn Lindeijer bjorn at lindeijer.nl
Mon Mar 28 08:44:43 PDT 2011


On Mon, Mar 28, 2011 at 17:32, Nuno Silva <little.coding.fox at gmail.com> wrote:
> On Mon, Mar 28, 2011 at 4:26 PM, ingmar wirths <ingmania at googlemail.com>
> wrote:
>> i'm getting a little frustrated trying to put the content of a packet
>> into a string.
>> What i simply want to do is something like:
>>
>> std::string my_string (packet->data, packet->dataLength);
>>
>> This doesn't compile however. I kind of get the idea why not, fiddled
>> around a little,
>> but could'nt get it working.
>>
>> I guess someone did this before, any ideas?
>
> First of all, be sure that the content you're getting is indeed a string.
> Binary data does not go well with strings, because e.g., std::string may
> find a '\0' before it reaches the end of the packet data which signifies an
> end of string in C-Style strings, and thus not have all the data.

Actually, a std::string has no problems with storing binary data and
is not necessarily null-terminated (it can contain 0 chars). The
length of a std::string is stored separately. A std::string does not
go looking for a 0 terminator when you pass in the length of the data
in the constructor, like ingmar is doing.

I think really the only problem could be that ENetPacket::data is a
enet_uint8* and should be cast to a char* for the std::string
constructor to accept it. So:

std::string my_string ((char*) packet->data, packet->dataLength);

Should compile and work fine.

Best regards,
Bjørn


More information about the ENet-discuss mailing list