Difference between revisions of "Converting everything to and from wxString"

From WxWiki
Jump to navigation Jump to search
Line 57: Line 57:
 
wxString number(wxT("3.14159"));
 
wxString number(wxT("3.14159"));
 
double value;
 
double value;
if(!s.ToDouble(&value)); // error!
+
if(!s.ToDouble(&value)){ /* error! */ }
 
</source>
 
</source>
  

Revision as of 13:09, 4 January 2008

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;

float to wxString

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

or

wxString mystring;
mystring << myfloat;

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());