如何在C++中将CString
转换为double
?
同时支持Unicode会更好。
谢谢!
如何在C++中将CString
转换为double
?
同时支持Unicode会更好。
谢谢!
CString
可以转换为LPCTSTR
,它基本上是一个const char*
(在Unicode版本中为const wchar_t*
)。
知道了这一点,您可以使用atof()
:
CString thestring("13.37");
double d = atof(thestring).
...或者对于 Unicode 构建,可以使用_wtof()
函数:
CString thestring(L"13.37");
double d = _wtof(thestring).
...或者支持Unicode和非Unicode构建...
CString thestring(_T("13.37"));
double d = _tstof(thestring).
(_tstof()
是一个宏,根据 _UNICODE
是否被定义,会扩展为 atof()
或者 _wtof()
)
使用std::stringstream
,您可以将任何东西转换为任何东西。唯一的要求是实现运算符>>
和<<
。字符串流可以在<sstream>
头文件中找到。
std::stringstream converter;
converter << myString;
converter >> myDouble;
CString
对象一起使用。你也不需要一个operator<<()
。这就是构造函数的作用:std::wstringstream converter(myString);
。请注意,这需要一个CStringW
(在大多数情况下,这是正确的类型)。然而,仍然存在一个潜在的问题。它似乎很清晰、优雅,但是错误的。它使用当前线程区域设置进行转换。这可能是你想要的,也可能不是。最好使用一种允许你明确指定转换所使用的区域设置的解决方案。 - IInspectable#include <boost/lexical_cast.hpp>
using namespace boost;
...
double d = lexical_cast<double>(thestring);