How to convert a CString
object to integer in MFC.
If you are using TCHAR.H
routine (implicitly, or explicitly), be sure you use _ttoi()
function, so that it compiles for both Unicode and ANSI compilations.
More details: https://msdn.microsoft.com/en-us/library/yd5xkb5c.aspx
The problem with the accepted answer is that it cannot signal failure. There's strtol
(STRing TO Long) which can. It's part of a larger family: wcstol
(Wide Character String TO Long, e.g. Unicode), strtoull
(TO Unsigned Long Long, 64bits+), wcstoull
, strtof
(TO Float) and wcstof
.
Define in msdn: https://msdn.microsoft.com/en-us/library/yd5xkb5c.aspx
int atoi(
const char *str
);
int _wtoi(
const wchar_t *str
);
int _atoi_l(
const char *str,
_locale_t locale
);
int _wtoi_l(
const wchar_t *str,
_locale_t locale
);
CString is wchar_t string. So, if you want convert Cstring to int, you can use:
CString s;
int test = _wtoi(s)
i've written a function that extract numbers from string:
int SnirElgabsi::GetNumberFromCString(CString src, CString str, int length) {
// get startIndex
int startIndex = src.Find(str) + CString(str).GetLength();
// cut the string
CString toreturn = src.Mid(startIndex, length);
// convert to number
return _wtoi(toreturn); // atoi(toreturn)
}
Usage:
CString str = _T("digit:1, number:102");
int digit = GetNumberFromCString(str, _T("digit:"), 1);
int number = GetNumberFromCString(str, _T("number:"), 3);
CString s;
int i;
i = _wtoi(s); // if you use wide charater formats
i = _atoi(s); // otherwise
CString s="143";
int x=atoi(s);
or
CString s=_T("143");
int x=_toti(s);
atoi
will work, if you want to convert CString
to int
.