views:

1325

answers:

4

How do I convert a CString to a double in C++?

Unicode support would be nice also.

Thanks!

A: 

strtod (or wcstod) will convert strings to a double-precision value.

(Requires <stdlib.h> or <wchar.h>)

kitchen
Consider some more context to the page you're adding
Dave Hillier
Updated my post!
kitchen
Usage examples wouldn't go amiss either... See the accepted answer.
Shog9
+9  A: 

A CString can convert to an LPCTSTR, which is basically a const char* (const wchar_t* in Unicode builds).

Knowing this, you can use atof():

CString thestring("13.37");
double d = atof(thestring).

...or for Unicode builds, _wtof():

CString thestring(L"13.37");
double d = _wtof(thestring).

...or to support both Unicode and non-Unicode builds...

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)

Silfverstrom
This link shows you "wcstod" which is what I used to support unicode. http://msdn.microsoft.com/en-us/library/kxsfc1ab(VS.80).aspx
Steve Duitsman
This works, but IMO MighMoS's suggestion of std::stringstream is a bit cleaner.
Pete
+4  A: 

with the boost lexical_cast library, you do

#include <boost/lexical_cast.hpp>
using namespace boost;

...

double d = lexical_cast<double>(thestring);
Sahasranaman MS
+4  A: 

You can convert anything to anything using a std::stringstream. The only requirement is that the operators >> and << be implemented. Stringstreams can be found in the <sstream> header file.

std::stringstream converter;
converter << myString;
converter >> myDouble;
MighMoS