Reputation: 5856
Converting CString
to an int
in ASCII mode is as simple as
CString s("123");
int n = atoi(s);
However that doesn't work for projects in UNICODE mode as CString
becomes a wide-char string.
How do I write my code to cover both ASCII and UNICODE modes without extra if
statements?
Upvotes: 0
Views: 2988
Reputation: 308206
There's a special version of CString
that uses multibyte characters even if your build is specified for wide characters - CStringA
. It will also convert from wide characters automatically.
CString s(_T("123"));
CStringA sa = s;
int n = atoi(sa);
There's a corresponding CStringW
that only uses wide characters.
Upvotes: 3
Reputation: 5856
Turns out there's a _ttoi()
available just for that purpose:
CString s( _T("123") );
int n = _ttoi(s);
This works for both modes with no extra effort.
If you need to convert hexadecimal (or other-base) numbers you can resort to a more generic strtol()
variant:
CString s( _T("0xFA3") );
int n = _tcstol(s, nullptr, 16);
Upvotes: 4