[ENet-discuss] ENetPacket to std::string

Nuno Silva little.coding.fox at gmail.com
Mon Mar 28 08:32:07 PDT 2011


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.

You could typecast that packet->data as (const char *)packet->data, however
it probably does not have an ending '\0', so you should first copy it to a
buffer and append a '\0' to that buffer. Something like this:

std::vector<char> myString(packet->dataLength + 1);
myString[packet->dataLength] = '\0';
memcpy(&myString[0], packet->data, packet->dataLength);

std::string my_string(&myString[0]);

Hope that helps.

On Mon, Mar 28, 2011 at 4:26 PM, ingmar wirths <ingmania at googlemail.com>wrote:

> Hi,
>
> 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?
>
> Thanks,
> ingmar
> _______________________________________________
> ENet-discuss mailing list
> ENet-discuss at cubik.org
> http://lists.cubik.org/mailman/listinfo/enet-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.cubik.org/pipermail/enet-discuss/attachments/20110328/d0e96986/attachment.html>


More information about the ENet-discuss mailing list