How to convert a CString
object to integer in MFC.
11 Answers
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 simplest approach is to use the atoi()
function found in stdlib.h
:
CString s = "123";
int x = atoi( s );
However, this does not deal well with the case where the string does not contain a valid integer, in which case you should investigate the strtol()
function:
CString s = "12zzz"; // bad integer
char * p;
int x = strtol ( s, & p, 10 );
if ( * p != 0 ) {
// s does not contain an integer
}
The canonical solution is to use the C++ Standard Library for the conversion. Depending on the desired return type, the following conversion functions are available: std::stoi, std::stol, or std::stoll (or their unsigned counterparts std::stoul, std::stoull).
The implementation is fairly straight forward:
int ToInt( const CString& str ) {
return std::stoi( { str.GetString(), static_cast<size_t>( str.GetLength() ) } );
}
long ToLong( const CString& str ) {
return std::stol( { str.GetString(), static_cast<size_t>( str.GetLength() ) } );
}
long long ToLongLong( const CString& str ) {
return std::stoll( { str.GetString(), static_cast<size_t>( str.GetLength() ) } );
}
unsigned long ToULong( const CString& str ) {
return std::stoul( { str.GetString(), static_cast<size_t>( str.GetLength() ) } );
}
unsigned long long ToULongLong( const CString& str ) {
return std::stoull( { str.GetString(), static_cast<size_t>( str.GetLength() ) } );
}
All of these implementations report errors through exceptions (std::invalid_argument if no conversion could be performed, std::out_of_range if the converted value would fall out of the range of the result type). Constructing the temporary std::[w]string
can also throw.
The implementations can be used for both Unicode as well as MBCS projects.
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);