Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Return entire null separated string

Tags:

c++

char

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?

like image 285
Elan Hickler Avatar asked Mar 14 '23 21:03

Elan Hickler


1 Answers

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++.

like image 123
Dietmar Kühl Avatar answered Mar 23 '23 10:03

Dietmar Kühl