I want to convert a char buffer of known size (e.g. received from socket) into a string, but with the caveat that the char array is not necessarily null-terminated.
So I tried to use string (InputIterator first, InputIterator last)
constructor.
However,
I notice that string::length()
isn't always the same as strlen
,
at least in my case where strings are manually crafted from buffers
with many trailing zeros.
#include <string>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char a[20] {0};
a[0] = 'a';
string b(a, a + 20);
cout << b.length() << endl;
cout << strlen(b.c_str()) << endl;
}
Output is
20
1
Though this is a well-defined behavior for string::length
(thanks to the comments and some initial answers for helping me to realize that), I'd like to find a better / more idiomatic solution.