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.
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.
Actually, as of C++11 std::string is guaranteed to be null terminated. Specifically, s[s. size()] will always be '\0' .
The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by '\0'). When we write some string using double quotes (“…”), then it is converted into null terminated strings by the compiler.
strlen(s) returns the length of null-terminated string s. The length does not count the null character.
Many ways to do this; but probably the one to me that seems to be most "C++" rather than C is:
str.erase(std::find(str.begin(), str.end(), '\0'), str.end());
i.e. Erase everything from the first null to the end.
You can do this:
buffer.erase(std::find(buffer.begin(), buffer.end(), '\0'), buffer.end());
Consider std::basic_string::erase
has an overloading:
basic_string& erase( size_type index = 0, size_type count = npos );
A more succinct way:
buffer.erase(buffer.find('\0'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With