c++ memcpy string to char*

Feb 1, 2010 at 11:02pm
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 Feb 1, 2010 at 11:04pm
Feb 1, 2010 at 11:08pm
If line is an std::string, use line.c_str() instead of &line
Feb 1, 2010 at 11:11pm
also be sure you malloc length()+1 chars
Feb 1, 2010 at 11:15pm
But line.c_str () terminates at the first null character it sees on every line. I need to preserve the null chars.
Feb 1, 2010 at 11:21pm
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)
Feb 1, 2010 at 11:24pm
Right , so how do I convert the string then ? You have any ideas?
Feb 1, 2010 at 11:31pm
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.
Feb 1, 2010 at 11:34pm
or he simply reserves +1 space and appends the '\0'-char at the end...
Feb 1, 2010 at 11:38pm
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 Feb 1, 2010 at 11:40pm
Feb 2, 2010 at 10:48pm
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
Feb 2, 2010 at 11:59pm
Exactly.
Topic archived. No new replies allowed.