2012-05-12 62 views
-1

一些身体帮我就以下问题转换的CString的浮动

strFixFactorSide = _T("0.5"); 
dFixFactorSide = atof((const char *)(LPCTSTR)strFixFactorSide); 

“dFixFactorSide”取值为0.0000;

我该如何获得正确的价值?

回答

0

我认为你的CString strFixFactorSide是一个Unicode(UTF-16)字符串。

如果是这样,铸造(const char *)只改变指针类型,但它指向的字符串仍然是Unicode。

atof()不适用于Unicode字符串。如果您将L"0.5"放入其中,它将读取字节0x30('0')和0x00(也是UTF-16'0'的一部分),将其视为NUL终止的ASCII字符串"0"并将其转换为0.0。

如果CString strFixFactorSide是一个Unicode字符串,您需要首先将其转换为ASCII字符串,然后应用atof()或使用能够将Unicode字符串转换为数字的函数。 _wtof()可用于Unicode字符串。

+0

我得到错误为“错误C2065:'_wtof':未声明的标识符”。我使用eVC++ 4.0 – Vaibhav

+0

你试过包括'','','',''吗?其他人尝试:'wcstod()'或'swscanf()'。 –

+0

我得到如下解决方案“_stscanf(strFixFactorSide,_T(”%lf“),&dFixFactorSide);”但这是正确的方式吗? – Vaibhav

1

使用_tstof()而不是atof(),并将CString强制转换为LPCTSTR,并保持原样,而不是试图将其转换为const char *。在使用unicode时只能使用const _TCHAR *(LPCTSTR),请忘记const char *(LPCSTR)。

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) 
{ 
    int nRetCode = 0; 

    CString s1 = _T("123.4"); 
    CString s2 = _T("567.8"); 

    double v1 = _tstof((LPCTSTR)s1); 
    double v2 = _tstof((LPCTSTR)s2); 

    _tprintf(_T("%.3f"), v1 + v2); 

    return nRetCode; 
} 

并正确运行这个预期的答案。