如何在 C++ 中将 CString 转换为双精度值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/916790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a CString to a double in C++?
提问by Steve Duitsman
How do I convert a CString
to a double
in C++?
如何在 C++ 中将CString
a转换为 a double
?
Unicode support would be nice also.
Unicode 支持也很好。
Thanks!
谢谢!
回答by Silfverstrom
A CString
can convert to an LPCTSTR
, which is basically a const char*
(const wchar_t*
in Unicode builds).
ACString
可以转换为 an LPCTSTR
,这基本上是 a const char*
(const wchar_t*
在 Unicode 版本中)。
Knowing this, you can use atof()
:
知道这一点,您可以使用atof()
:
CString thestring("13.37");
double d = atof(thestring).
...or for Unicode builds, _wtof()
:
...或对于 Unicode 构建,_wtof()
:
CString thestring(L"13.37");
double d = _wtof(thestring).
...or to support both Unicode and non-Unicode builds...
...或同时支持 Unicode 和非 Unicode 构建...
CString thestring(_T("13.37"));
double d = _tstof(thestring).
(_tstof()
is a macro that expands to either atof()
or _wtof()
based on whether or not _UNICODE
is defined)
(_tstof()
是一个宏,扩展为atof()
或_wtof()
基于是否_UNICODE
定义)
回答by MighMoS
You can convert anything to anythingusing a std::stringstream
. The only requirement is that the operators >>
and <<
be implemented. Stringstreams can be found in the <sstream>
header file.
您可以将任何东西任何东西使用std::stringstream
。唯一的要求是操作符>>
和<<
被执行。Stringstreams 可以在<sstream>
头文件中找到。
std::stringstream converter;
converter << myString;
converter >> myDouble;
回答by Sahas
with the boost lexical_cast library, you do
使用 boost lexical_cast 库,你可以
#include <boost/lexical_cast.hpp>
using namespace boost;
...
double d = lexical_cast<double>(thestring);