我正在尝试将一个字符串复制到 char 数组,字符串有多个 NULL 字符。我的问题是当第一个 NULL 字符遇到我的程序停止复制字符串时。
我使用了两种方法。这就是我到目前为止的情况。
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
std::string str = "Hello World.\0 How are you?\0";
char resp[2000];
int i = 0;
memset(resp, 0, sizeof(resp));
/* Approach 1*/
while(i < str.length())
{
if(str.at(i) == '\0')
str.replace(str.begin(), str.begin()+i, " ");
resp[i] = str.at(i);
i++;
}
/* Approach 2*/
memcpy(resp, str.c_str(), 2000);
cout << resp << endl;
return 0;
}
该程序应打印Hello World. How are you?
. 请帮我纠正这个问题。