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 ?
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.
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)
{
constchar* 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.