I need to give a function a null terminated character sequence, but I can't figure out how to go from string literal ultimately to a char pointer. Problem is demonstrated here:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
std::string str ("this\0is a\0null separated\0string");
std::cout << "The size of str is " << str.size() << " bytes.\n\n";
return 0;
}
my current code works..
std::string tmp = g_apidefs[i].ret_val +'.'+ g_apidefs[i].parm_types +'.'+ g_apidefs[i].parm_names +'.'+ g_apidefs[i].html_help;
size_t length = 1+strlen(tmp.c_str());
g_apidefs[i].dyn_def = new char[length];
memcpy(g_apidefs[i].dyn_def, tmp.c_str(), length);
char* p = g_apidefs[i].dyn_def;
while (*p) { if (*p=='.') *p='\0'; ++p; }
ok &= rec->Register(g_apidefs[i].regkey_def, g_apidefs[i].dyn_def) != 0;
...it turns .
into \0
, but is there any way to just have \0
in the first place? I was originally using strdup (a few less lines of code) but had some platform-specific incompatibility issues.
I'm wondering if there's a C++11 or C++14 way of dealing with this?
You can use a char
array and initialize your string using iterators to this array, e.g.:
template <int N>
std::string make_string(char const (&array)[N]) {
return std::string(array, array + N);
}
int main() {
std::string s = make_string("foo\0bar");
}
As defined the string will also contain the terminating null character. Just subtract 1
if that's not desired. This works with all versions of C++.
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