1
votes

i want to convert CString to const char*, i used that const char* cstr = (LPCTSTR)CString; but it doesn't compile,so how to do that, or how to convert CString to double, i used this method _tstof but it returns 0 when i passed a CString to it, so i want to convert CString to const char* inorder to pass the converted value to the method atof(), here's an example:

int nTokenPos=0;
CString leftDigit,rightDigit;
double firstNum,secondNum;

if(dialog->myValue.Find('X')!=-1){
CString resToken = dialog->myValue.Tokenize(_T("X"), nTokenPos);
leftDigit=resToken;
OutputDebugString(leftDigit);
while(!resToken.IsEmpty())
{
   resToken = dialog->myValue.Tokenize(_T("X"), nTokenPos);
   rightDigit=resToken;
   rightDigit+="\n";
  //OutputDebugString(rightDigit);
}
 firstNum= _tstof(leftDigit);
 secondNum=_tstof(rightDigit);
 OutputDebugString(leftDigit);
 OutputDebugString(rightDigit);
 TRACE( "First_Number %d\n",firstNum); --->OutPuts ZERO
 TRACE( "\nSecond_Number %d\n",secondNum); --->OutPuts ZERO
//MathFuncs::MyMathFuncs::Multiply(firstNum,secondNum);
 TRACE( "The result %d\n",MathFuncs::MyMathFuncs::Multiply(firstNum,secondNum));
3
Could you show an example how you pass it in and get the result 0? - Joachim Isaksson

3 Answers

1
votes

This line

const char* cstr = (LPCTSTR)CString;

doesn't compile because I guess you are building an UNICODE build of your project and therefore _T expands to a 2-byte character (a wide character).

To make this conversion working you could use the ATL macros. Like:

USES_CONVERSION;
const char* cstr = T2A((LPCTSTR)CString);

However, this is not really related to your initial problem as you are using anyways _tstof() which handles the _T issues for you.

[Edited]:

The mistake is somewhere else. The format string of the TRACE is not using the wright placeholder for a float/double. Instead of %d use %f:

CString leftDigit = _T("12.5");
double  firstNum = _tstof(leftDigit);
TRACE(_T("%f\n"), firstNum);

I tried this and got 12.50000000 printed in the Output pane of VS.

0
votes

I am not sure if you are using UNICODE or not. You should use generic text mapping. Anyway:

CString csTest(_T("Test"));

const TCHAR* cstr = (LPTSTR)(LPCTSTR)csTest;
0
votes
CString s( _T( "ala bala portocala" ) );
 CStringA s2( s );
 const char* c = s2;