Link to home
Start Free TrialLog in
Avatar of abi_a
abi_a

asked on

convert CString data to integer

HI,
     How to convert a CString data to int. Suppose I have

char* bytearray;
CString data;
CString CSbytearray(bytearray);
data = CSbytearray.Mid(1,4);

Now,I need data in integer format. Can anyone help.
Avatar of Zoppo
Zoppo
Flag of Germany image

Hi abi_a,


if I understand correctly you have a string containing a number which you want to have as an 'int', correct?

for this you can use atoi function for this, i.e.

int num = atoi( (LPCTSTR)data );

hope that helps,

ZOPPO
Avatar of akalmani
akalmani

Alternately you can also use
int iVal = 0;
sscanf((LPCTSTR)data, &iVal);
Avatar of abi_a

ASKER

hi,
 
For  int num = atoi( (LPCTSTR)data ); I get compiler error
cannot convert from 'class CString' to 'const char *'

for sscanf((LPCTSTR)data, &iVal); getting
'sscanf' : cannot convert parameter 1 from 'const unsigned short *' to 'const char *'

hm ... that's strange ... try these:

num = atoi( data );
num = atoi( (LPTSTR)data );

BTW, I find this is strange: LPCTSTR of a CString should always work since LPCTSTR
is a conversion operator of CString class in MFC
seems strange for me too..
maybe you can try this
sscanf(data.GetBuffer(data.GetLength()), &iVal);
can you show us some code
Avatar of abi_a

ASKER

Am getting same error.Iam coding in embedded vc++. Does that make any difference.

thanks
Well, I guess so ... I only found in MSDN that MFC for Windows CE CString has an operator LPCTSTR ...

maybe you can call it in another way, i.e. as function instead as operator
num = atoi( LPCTSTR( data ) );

Unfortunateley I have no further experience with embedded vc++, sorry ...

ZOPPO
Avatar of abi_a

ASKER

my code goes like this.....

CString data;
CString CSbytearray(bytearray);  // bytearray is a char array
data = CSbytearray.Mid(1,4);
 
In data I get something like 12 as a string. I need to convert it to int.
ASKER CERTIFIED SOLUTION
Avatar of vijay_visana
vijay_visana

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
OPPSs...

TCHAR sz[1024];

lstrcpy(sz, data);
num =  _ttoi((LPCTSTR)sz);

Seems that CString is using UNICODE and the other functions we mentioned are just using ANSI
Last try from me since I too do not have any experience in eVC++

int iVal = 0;
_stscanf(data.GetBuffer(data.GetLength()), _T("%d"), &iVal);

Slight modification to Zoppo's solution, try something like this
iVal = _ttoi(data.GetBuffer(data.GetLength()));
Sorry too late in submission...did not refresh before submitting
Avatar of abi_a

ASKER


well     num = _ttoi((LPCTSTR)data);
  works fine

thanks very much