I'm using a std::string
to interface with a C-library that requires a char*
and a length field:
std::string buffer(MAX_BUFFER_SIZE, '\0');
TheCLibraryFunction(&buffer[0], buffer.size());
However, the size()
of the string is the actual size, not the size of the string containing actual valid non-null characters (i.e. the equivalent of strlen()
). What is the best method of telling the std::string
to reduce its size so that there's only 1 ending null terminator character no explicit null terminator characters? The best solution I can think of is something like:
buffer.resize(strlen(buffer.c_str()));
Or even:
char buffer[MAX_BUFFER_SIZE]{};
TheCLibraryFunction(buffer, sizeof(buffer));
std::string thevalue = buffer;
Hoping for some built-in / "modern C++" way of doing this.
EDIT
I'd like to clarify the "ending null terminator" requirement I mentioned previously. I didn't mean that I want 1 null terminator explicitly in std::string
's buffer, I was more or less thinking of the string as it comes out of basic_string::c_str()
which has 1 null terminator. However for the purposes of the resize()
, I want it to represent the size of actual non-null characters. Sorry for the confusion.