Page 1 of 1

wxString and '\0'

Posted: Wed Jun 18, 2008 7:43 am
by normunds
Is it possible to save '\0' character into wxString? If not, what is preferred way to save zero values into string? wxChar[], wxCharBuffer, char[] or other?

At the end I should convert that content to char *

Posted: Wed Jun 18, 2008 8:56 am
by Grrr
wxString is for C style 0-terminated strings. I think storing '\0' will cause problems. Maybe wxMemoryBuffer is a better alternative?

Posted: Wed Jun 18, 2008 9:55 am
by Jorg
You can store any character in a wxString. You can even read a file to it, write it back later without any problems (in ANSI mode). But if you use the c_str() conversion method that exports the buffer of a wxString as a const char * and you send it to a normal c style method, it will stop reading the string when the first \0 is encountered.

- Jorgen

Posted: Wed Jun 18, 2008 10:59 am
by normunds
Jorg wrote:You can store any character in a wxString. You can even read a file to it, write it back later without any problems (in ANSI mode). But if you use the c_str() conversion method that exports the buffer of a wxString as a const char * and you send it to a normal c style method, it will stop reading the string when the first \0 is encountered.

- Jorgen
Actually I was trying to append '\0' char with += and Append methods without result. That all in Unicode mode. But if there is no possibility to export that string to char* then I will look for another way, where to store this string.

Posted: Wed Jun 18, 2008 6:16 pm
by Auria
normunds wrote:But if there is no possibility to export that string to char* then I will look for another way, where to store this string.
If what you're trying to do is convert a wxString to a C-style char*, just use mb_str() method

Posted: Thu Jun 19, 2008 6:22 am
by normunds
OK, my mistake, you can append to wxString '\0' symbol, but you can't do such:

Code: Select all

wxString c = _T("\x00");
int len = c.Length(); // len is 0
Why?

Posted: Thu Jun 19, 2008 9:45 am
by doublemax
if you want to create a string with 0-bytes, you must pass the number of chars to the ctor. How else should the code know where your string ends?

Code: Select all

{
	wxChar teststring1[]=wxT("wx");
	wxString s1(teststring1);
	wxLogMessage(wxT("'%s' (%d)"), s1, s1.Len());

	wxChar teststring2[]=wxT("wx\x00wx");
	wxString s2(teststring2);
	wxLogMessage(wxT("'%s' (%d)"), s2, s2.Len());

	wxChar teststring3[]=wxT("wx\x00wx");
	wxString s3(teststring3, 5);
	wxLogMessage(wxT("'%s' (%d)"), s3, s3.Len());

	wxChar teststring4[]=wxT("\x00");
	wxString s4(teststring4, 1);
	wxLogMessage(wxT("'%s' (%d)"), s4, s4.Len());
}
output:
11:50:20: 'wx' (2)
11:50:20: 'wx' (2)
11:50:20: 'wx' (5)
11:50:20: '' (1)
However, even if it's possible, i personally think a string should not be used to store random binary data.