我需要给一个函数一个空终止的字符序列,但我无法弄清楚如何从字符串文字最终到一个字符指针.问题在这里展示:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我目前的代码有效..
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;
Run Code Online (Sandbox Code Playgroud)
......它变成.了\0,但是有没有办法\0在第一时间拥有?我最初使用strdup(少了几行代码),但有一些特定于平台的不兼容问题.
我想知道是否有C++ 11或C++ 14处理这个问题的方法?
您可以使用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");
}
Run Code Online (Sandbox Code Playgroud)
根据定义,字符串还将包含终止空字符.只是减去1这是不是想要的.这适用于所有版本的C++.