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);
.. copies 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-artifacts like string.h and strnlen() (and it's ugly).
How would I do this in modern C++?
A C-buffer provided to any sort of writing functionFor this situation I'd pre-allocate an extra charchar buffer[n+1]; buffer[n] = 0;. Then usestd::string(buffer)as the string is always null-terminated.