Converting everything to and from wxString

From WxWiki
Jump to navigation Jump to search

This question seems common so I thought I'd write an article. Note that sometimes there may be more than one possible solutions, so don't forget to check the docs.

Note that it is recommended to use wxString as much as possible. Do no use char* or std::string unless you use a third-party library requires it.

Literals

A literal is a string written in code with "quotes around it". A char* is not a literal, and a wxString or a std::string neither. Unicode builds (prior to wxWidgets 3) require you to use one of these macros:

_("text that can be translated")
wxT("text that can't be translated")
_T("same as wxT")

char* c = "sometext";
wxT(c) // WRONG, not a literal

char* to wxString

char* chars = "Hello world";
wxString mystring(chars, wxConvUTF8);

wxString to char*

wxString mystring(wxT("HelloWorld"));
const char* cstring = mystring.mb_str();

int to wxString

wxString mystring = wxString::Format(wxT("%i"),myint);

or

wxString mystring;
mystring << myint;

or

wxString int_to_wxString(int i)
{
	char buffer[10];
	sprintf (buffer, "%d", i);

	return wxString(buffer, wxConvUTF8);
}

float to wxString

wxString mystring = wxString::Format(wxT("%f"), myfloat);

or

wxString mystring;
mystring << myfloat;

or

wxString float_to_wxString(float f)
{
	char buffer[16];
	sprintf (buffer, "%f", f);
	return wxString(buffer, wxConvUTF8);
}

wxString to integer number

wxString number(wxT("145"));
long value;
if(!s.ToLong(&value)); // error!

wxString to floating-point number

wxString number(wxT("3.14159"));
double value;
if(!s.ToDouble(&value)); // error!

std::string to wxString

std::string stlstring = "Hello world";
wxString mystring(stlstring.c_str(), wxConvUTF8);

wxString to std::string

wxString mystring(wxT("HelloWorld"));
std::string stlstring = std::string(mystring.mb_str());