0

I am trying to copy one string to char array, string have multiple NULL character. My problem is when first NULL character encountered my program stops copying the string.

I have used two approaches. This is what I am so far.

#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;
}

This program should print Hello World. How are you?. Please help me to correct this.

3
  • 1
    If you print str.length(), is it 12 or 24(ish)? I think your initialization is wrong. You will need to insert the 0 in the middle manually. Commented Apr 7, 2014 at 8:41
  • @MatsPetersson... Thanks mat it is 12 only. Commented Apr 7, 2014 at 8:44
  • I believe cout should output string only to the first zero byte anyway, am I wrong? Commented Apr 7, 2014 at 9:06

2 Answers 2

1

You could also one-shot it with

std::transform(
  str.begin(), str.end(), resp, [](char c) { return c == '\0' ? ' ' : c; }
);

Of course as @Mats has mentioned your string doesn't have any null chars, strings can also be initialized as follows though:

char const cstr[] = "Hello World.\0 How are you?";
std::string str(cstr, sizeof cstr);

C++14 has a std::string literal operator

std::string str = "Hello World.\0 How are you?"s;
Sign up to request clarification or add additional context in comments.

1 Comment

This includes the trailing null also; possibly sizeof cstr - 1 was intended
0

Use std::copy:

std::copy(str.begin(), str.end(), std::begin(resp));

followed by std::replace:

std::replace(std::begin(resp), std::begin(resp) + str.size(), '\0', ' ');

You may want to define your character array so that it is full of zeros at the start:

char resp[2000] = {};

3 Comments

stringtoarray.cpp:23: error: begin' is not a member of std'
@someone You must be compiling with a pre-C++11 compiler. You can use &resp[0] instead.
Of course, that won't help the fact that the std::string is only initialized with the C-style string up to the first zero. You can have a std::string with NUL-characters in it, but you can't get it from a C-style string (in the way the original code does, at least).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.