Convert MFC CString to integer

2019-01-17 19:32发布

How to convert a CString object to integer in MFC.

10条回答
贼婆χ
2楼-- · 2019-01-17 19:35

A _ttoi function can convert CString to integer, both wide char and ansi char can work. Below is the details:

CString str = _T("123");
int i = _ttoi(str);
查看更多
贪生不怕死
3楼-- · 2019-01-17 19:36

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
}
查看更多
smile是对你的礼貌
4楼-- · 2019-01-17 19:52

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
}
查看更多
\"骚年 ilove
5楼-- · 2019-01-17 19:53

You may use the C atoi function ( in a try / catch clause because the conversion isn't always possible) But there's nothing in the MFC classes to do it better.

查看更多
看我几分像从前
6楼-- · 2019-01-17 20:00

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.

查看更多
放我归山
7楼-- · 2019-01-17 20:01

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

查看更多
登录 后发表回答