c++ memcpy string to char*

Hello,

I have a string that contains null characters in the middle. I am trying to convert it to a char *. I am new to c++ and I see that using c_str for example will terminate at the first null character.

I am trying memcpy like this:
while (! myfile.eof() )
{
getline (myfile,line);
char * cstr;
cstr = (char *) malloc(sizeof(char)*(line.length()));
memcpy(cstr, &line, line.length()+1);

}

How ever, the memcpy is failing to copy the entire string including the null character for some reason. What am I doing wrong here ?

Thanks
Last edited on
If line is an std::string, use line.c_str() instead of &line
also be sure you malloc length()+1 chars
But line.c_str () terminates at the first null character it sees on every line. I need to preserve the null chars.
c_str gives you a straight dump of the characters in the string. It doesn't change/remove any of them.

What's more likely happening is the output stops printing at the first null (since the null indicates the end of the string usually)
Right , so how do I convert the string then ? You have any ideas?
There is no way to preserve null characters in a C-string because they are used to determine it's end. Well, technically, you could also have the size stored somewhere but too many C-string functions assume the size is until the null character so that won't really help. You are probably just better off using strings for everything and avoiding C-strings except where necessary.
or he simply reserves +1 space and appends the '\0'-char at the end...
as mentioned above (c_str())

The problem isn't with converting. You're converting properly. The problem is with printing.

Since you're no longer using the null terminator to mark the end of the string, you need to write your own function to print it.

here's something you can do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void PrintStringWithNulls(ostream& stream, const string& str)
{
  const char* s = str.c_str();

  unsigned pos = 0;

  while(pos < str.length())
  {
    stream << (s + pos);
    stream << /*output whatever you want to represent a null character here*/;

    pos += strlen(s) + 1;
  }
}




EDIT: this is just assuming a normal << operation doesn't work on a std::string with nulls -- which I just assumed was the case but didn't actually test because I'm at work.
Last edited on
Hi Disch,

So, what you are saying is this:

memcpy a string into c_str will work fine given the string length, even if the string contains null in the middle.

How ever, printing or trying to stream it will stop at the first null character it sees. Correct?

-ramsci
Exactly.
Topic archived. No new replies allowed.