52

How to convert a CString object to integer in MFC.

Ajay
  • 18,086
  • 12
  • 59
  • 105

12 Answers12

44

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

sergiol
  • 4,122
  • 4
  • 47
  • 81
Vladimir Kocjancic
  • 1,814
  • 3
  • 22
  • 34
42

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
}
Ajay
  • 18,086
  • 12
  • 59
  • 105
  • 9
    stumbled here beacause the compiler says: "atoi: cannot convert CString to const char *"; then I discovered your answer does not work if it is an unicode project, _ttoi is better as pointed out by Unagi – Zac Feb 28 '14 at 17:13
  • 3
    error C2664: 'atoi' : cannot convert parameter 1 from 'CString' to 'const char *' – Sameera Kumarasingha Apr 10 '15 at 08:35
  • Now, MFC CString default use w_char which can not use atoi. – Ben Aug 10 '23 at 01:38
20
CString s;
int i;
i = _wtoi(s); // if you use wide charater formats
i = _atoi(s); // otherwise
PaV
  • 737
  • 4
  • 7
  • 1
    You need to do something with the return values of those functions for this code to be useful. –  Jun 14 '09 at 14:09
16

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);
chappjc
  • 30,359
  • 6
  • 75
  • 132
Jerry Young
  • 161
  • 1
  • 3
9

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
  • 2,357
  • 3
  • 32
  • 41
4
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.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
sankar
  • 82
  • 5
3

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.

MSalters
  • 173,980
  • 10
  • 155
  • 350
3

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.

IInspectable
  • 46,945
  • 8
  • 85
  • 181
1

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)
Himanshu
  • 4,327
  • 16
  • 31
  • 39
HungVu
  • 21
  • 3
  • `CString` depends on the `_UNICODE` and `_MBCS` preprocessor symbols. It might store a UTF-16 encoded Unicode string, a DBCS characters string or an ASCII string. Suggesting that it would always be a Unicode string is just wrong, sorry. – IInspectable Dec 11 '15 at 12:13
1

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);
snir
  • 2,961
  • 1
  • 17
  • 10
0

Q: How to convert a CString object to integer in MFC?

A: The first requirement for the CString object is that it must contain only numbers. A string can contain a lot of digits, maybe more than an integer can handle. To be able to convert it to an integer, you also need to know how many digits fit in an integer in C++. This can vary per platform.

constexpr int maxdigits = std::numeric_limits<int>::digits10;

So you first have to cut string to size before you release a convert function on the CString object. A CString handles in UNICODE mode wchar_t characters, so you need something like _wtoi() to do the conversion.

T.Buys
  • 26
  • 3
-3

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Stephane Halimi
  • 408
  • 3
  • 5