tags:

views:

4377

answers:

4

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
+1  A: 
CString s;
int i;
i = _wtoi(s); // if you use wide charater formats
i = _atoi(s); // otherwise
PaV
You need to do something with the return values of those functions for this code to be useful.
anon
Yes, you are of course correct.
PaV
+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
+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