C ++ returns an integer null string

I need to give the function a null-terminated sequence of characters, but I cannot figure out how to go from the string literal to the char pointer eventually. The problem here is demonstrated:

#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 is working.

    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;

... he turns .in \0, but is there a way to just have it \0first? I originally used strdup (a few lines of code), but had some platform-specific incompatibility issues.

I am wondering if there is a C ++ 11 or C ++ 14 way with this?

+4
source share
3 answers

char , , :

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");
}

, . 1, . ++.

+7

, - :

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');
}
0

, , , , , .

// 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]);

@Dietmar KΓΌhl , , , .

. Stackoverflow , .

0

Source: https://habr.com/ru/post/1620191/


All Articles