I have a char buffer of known size (for simplicity, let's say a fixed-sized array) from which I would like to construct a std::string. The string in this buffer may be null-terminated or it may run up to and include the very last char. I wish to create a std::string containing the contents up to the first null byte or the end of the buffer, whichever comes first.
This seems like a common enough thing to want to do, but the solution is not immediately obvious to me while looking at the std::string API.
std::stringhas a constructor taking a range viaconst char *and a length, but this constructor happily continues past null bytes and copies them into the string.- Calling
std::strlen()on the buffer before constructing thestringis not an option asstrlenrequires the buffer to be null-terminated, which may not be the case. - We could use the above constructor to make a
std::stringcontaining nulls and then resize it down to just before the first null, but that wastes memory as thestringwill be over-allocated.
What is the best and/or idiomatic way to do this?
The answer, as with so many questions regarding the C++ standard library, is to think about the problem in terms of iterators.
std::stringhas a constructor taking two iterators,firstandlast. Thestringwill be created by copying fromfirstup until but not includinglast.So
firstshould obviously be the beginning of our buffer, whilelastshould either be the first null in our buffer or one past the end of the buffer. Conveniently, that is exactly what a call tostd::findsearching the buffer for'\0'will return.