Maybe it's just the lack of coffee, but I'm trying to create a std::string
from a null-terminated char
array with a known maximum length and I don't know, how to do it.
auto s = std::string(buffer, sizeof(buffer));
.. was my favorite candidate but since C++ strings are not null-terminated this command will copy sizeof(buffer)
bytes regardless of any contained '\0'.
auto s = std::string(buffer);
.. copyies from buffer
until \0
is found. This is almost what I want but I can't trust the receive buffer so I'd like to provide a maximum length.
Of course I can now integrate strnlen()
like this:
auto s = std::string(buffer, strnlen(buffer, sizeof(buffer)));
But that seems dirty - it traverses the buffer twice and I have to deal with C-artefacts like string.h
and strnlen()
(and it's ugly).
How would I do this in modern C++?
Aucun commentaire:
Enregistrer un commentaire