Elan Hickler
Elan Hickler

Reputation: 1139

C++ Return entire null separated string

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?

Upvotes: 4

Views: 149

Answers (3)

Elan Hickler
Elan Hickler

Reputation: 1139

Here's the answer I really needed, it's really simple, not sure how I spent hours trying to figure it out

// str is a global variable, so it is safe to reference it with &
string str = str1 + '\0' + str2 + '\0' + str3 + '\0' + str4;
func_that_needs_null_separated_str(&str[0]);

Thanks @Dietmar Kühl for the little tip that finally lead me to this conclusion.

Well good. Now this Stackoverflow question has answers to two problems dealing with null characters.

Upvotes: 0

Elan Hickler
Elan Hickler

Reputation: 1139

I'm posting my own answer as an alternative just in case someone finds it useful:

std::vector<std::string> str_vect ={ str1,str2,str3,str4 };

std::vector<char> char_arr
for (const auto& str : str_vect) {
    char_arr.insert(char_arr.end(), str.begin(), str.end());
    char_arr.push_back('\0');
}

Upvotes: 0

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

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

Upvotes: 7

Related Questions