mfcdoublecstring

How to convert CString to const char*?


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));

Solution

  • 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.