How do I convert a CString
to a double
in C++?
Unicode support would be nice also.
Thanks!
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.
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().
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.
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.
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)
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With