Steve Duitsman
Steve Duitsman

Reputation: 2791

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

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

Unicode support would be nice also.

Thanks!

Upvotes: 15

Views: 45980

Answers (4)

xian
xian

Reputation: 4693

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

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

Upvotes: 1

Silfverstrom
Silfverstrom

Reputation: 29322

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)

Upvotes: 34

MighMoS
MighMoS

Reputation: 1254

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;

Upvotes: 5

Sahas
Sahas

Reputation: 11399

with the boost lexical_cast library, you do

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

...

double d = lexical_cast<double>(thestring);

Upvotes: 3

Related Questions