Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert CString to double 2

Status
Not open for further replies.

der7

Programmer
Apr 28, 2005
6
0
0
GB
Hi there,

I've been trying to achieve this one way or another all day with no luck. I would like to convert a CString to a double.

For example, if my CString has the form -

CString testString("12345.6789");

I would like to be able to convert testString into a double so that e.g. double testData == 12345.6789

I have tried first converting the CString into a const char then converting this to a double but with no luck. Any help with how to get this working is much appreciated,

Many Thanks,


Dav
 
You can just use atof. A CString will convert to an LPCTSTR, which is basically a const char*, and atof takes a const char* argument.
Code:
CString testString("12345.6789");
double d = atof(testString);
 
Hi uolj,

Thanks for the reply. I've been trying to do it just like you suggest but I still get the error -

cannot convert parameter 1 from 'class CString' to 'const char *'

I've also tried doing this -

CString testString("12345.6789");
double d = atof((LPCSTR)testString);

but still get the same error message. I'm using Embedded Visual C++ 4, perhaps that is the problem? I have included <cstdio> and <cstdlib>, perhaps that operator is not in those libraries?

Thanks again for any tips,

Dav
 
Since the problem is that the CString is not converting to const char*, including those headers won't help (CString is declared somewhere else in Windows headers).

It is very likely that something is different with Embedded VC++ 4 compared to my VC++ 7.1 (where my code works). I'm not familiar with those differences, so all I can do is guess at a solution. Maybe try using GetBuffer().
 
It's impossible to cast Unicode CString to const char* (is it your case?). In such case try the library function (from <cstdlib>:
Code:
double wcstod( const wchar_t *nptr, wchar_t **endptr );
Use (LPCTSTR) casting for CString. May be it helps (sorry, I never work with Embedded C++)?..
 
Hi there,

Thanks for posting the code. I also managed to find similar code after doing some major googling last night. Basically, if you want to convert a CString to a double the wcstod operator is the way to go as ArkM rightly said.

Example -

CString testString("12345.123");
double d = wcstod(testString, NULL);

This will place the value 12345.123 into the double d.

Best,

David

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top