简体   繁体   中英

convert MFC's CString to int for both ASCII and UNICODE

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM