Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 615
Steve Duitsman Avatar asked May 27 '09 16:05

Steve Duitsman


People also ask

How do I convert a string to a double in C?

In the C Programming Language, the strtod function converts a string to a double. The strtod function skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn't a number.

How do you convert CString to float in MFC?

CString pi = "3.14"; return _ttof(pi); Reading a string value and parse/convert it to float allows you to locate the error when there is one. All you need is a help of a C Run-time function: strtod() or atof().

What does strtod do in C?

The strtod() is a builtin function in C and C++ STL which interprets the contents of the string as a floating point number and return its value as a double. It sets a pointer to point to the first character after the last valid character of the string, only if there is any, otherwise it sets the pointer to null.

How do I convert a double to a string in MFC?

A double can be converted into a string in C++ using std::to_string. The parameter required is a double value and a string object is returned that contains the double value as a sequence of characters.


2 Answers

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)

like image 169
Silfverstrom Avatar answered Oct 20 '22 22:10

Silfverstrom


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;
like image 24
MighMoS Avatar answered Oct 20 '22 20:10

MighMoS