Zwik
Zwik

Reputation: 654

How to get a C-string out of a string that contains \0 without losing the \0

I currently have a pretty huge string. I NEED to convert it into a C-string (char*), because the function I want to use only take C-string in parameter.

My problem here is that any thing I tried made the final C-string wayyy smaller then the original string, because my string contains many \0. Those \0 are essential, so I can't simply remove them :(...

I tried various way to do so, but the most common were :

myString.c_str();
myString.data();

Unfortunately the C-string was always only the content of the original string that was before the first \0.

Any help will be greatly appreciated!

Upvotes: 2

Views: 3919

Answers (5)

sbi
sbi

Reputation: 224089

You cannot create a C-string which contains '\0' characters, because a C-string is, by definition, a sequence of characters terminated by '\0' (also called a "zero-terminated string"), so the first '\0' in the sequence ends the string.

However, there are interfaces that take a a pointer to the first character and the length of the character sequence. These might be able to deal with character sequences including '\0'.

Watch out for myString.data(), because this returns a pointer to a character sequence that might not be zero-terminated, while mystring.c_str() always returns a zero-terminated C-string.

Upvotes: 8

Detmar
Detmar

Reputation: 733

This may not meet your needs, you did say 'Those \0 are essential', but how about escaping or replacing the '\0' chars?

Would one of these ideas work?

  1. replace the '\0' chars with a '\t' (tab char, decimal 9).
  2. replace the '\0' with some rarely used char value like decimal 1, or decimal 255.
  3. Create an escape code, say by replacing each '\0' char with a coded substring, (like octal as in "\000"). (Be sure to replace any original '\' with a coded value as well (like "\134")).

Upvotes: 0

Šimon Tóth
Šimon Tóth

Reputation: 36433

I'm a bit confused, but:

string x("abc");
if (x.c_str()[3] == '\0')
{ cout << "there it is" << endl; }

Upvotes: 0

Billy ONeal
Billy ONeal

Reputation: 106549

This is not possible. The null is the end of a null terminated string. If you take a look at your character buffer (use &myString[0]), you'll see that the NULLs are still there. However, no C functions are going to interpret those NULLs correctly because NULL is not a valid value in the middle of a string in C.

Upvotes: 3

dennycrane
dennycrane

Reputation: 2331

Well, myString has probably been truncated at construction/assignment time. You can try std::basic_string::assign which takes two iterators as arguments or simply use std::vector <char>, the latter being more usual in your use case. And your API taking that C string must actually support taking a char pointer together with a length.

Upvotes: 0

Related Questions