How to convert a CString to integer in MFC (VC++ 6.0)
+6
A:
The simplesr 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
}
anon
2009-06-14 12:49:37
+1
A:
CString s;
int i;
i = _wtoi(s); // if you use wide charater formats
i = _atoi(s); // otherwise
PaV
2009-06-14 12:51:00
You need to do something with the return values of those functions for this code to be useful.
anon
2009-06-14 14:09:41
Yes, you are of course correct.
PaV
2009-06-14 14:48:25
+1
A:
you can also use good old sscanf.
CString s;
int i;
int j = _stscanf(s, _T("%d"), &i);
if (j != 1)
{
// tranfer didn't work
}
BrianK
2009-06-17 02:22:27
+1
A:
If you are using TCHAR.H routine, be sure you use _ttoi() function.
More details: http://msdn.microsoft.com/en-us/library/hc25t012%28VS.71%29.aspx
Vladimir Kocjancic
2010-06-24 12:54:01