Wie konvertiere ich einen CString in C++ in ein Double?

Wie konvertiere ich einen CString in C++ in ein Double?


Wie konvertiere ich einen CString zu einem double in C++?


Unicode-Unterstützung wäre auch schön.


Danke!


Antworten:


Ein CString kann in einen LPCTSTR konvertiert werden , was im Grunde ein const char* ist (const wchar_t* in Unicode-Builds).


Wenn Sie dies wissen, können Sie atof() verwenden :


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

...oder für Unicode-Builds _wtof() :


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

...oder um sowohl Unicode- als auch Nicht-Unicode-Builds zu unterstützen...


CString thestring(_T("13.37"));
double d = _tstof(thestring).

(_tstof() ist ein Makro, das entweder zu atof() erweitert wird oder _wtof() basierend darauf, ob _UNICODE oder nicht definiert ist)


Einige Code-Antworten


double strtod(const char *nptr, char **endptr);
#include <stdlib.h>
/* Example using strtod by TechOnTheNet.com */  #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc, const char * argv[]) {
/* Define temporary variables */
char value[10];
char *eptr;
double result;
/* Copy a value into the variable */
/* It's okay to have whitespace before the number */
strcpy(value, "
958");
/* Convert the provided value to a double */
result = strtod(value, &eptr);
/* If the result is 0, test for an error */
if (result == 0)
{
/* If the value provided was out of range, display a warning message */
if (errno == ERANGE) printf("The value provided was out of range\n");
}
/* Display the converted result */
printf("%f decimal\n", result);
/* Copy a hexadecimal value into the variable */
strcpy(value, "0x8b2");
/* Convert the hexadecimal provided value to a double */
result = strtod(value, &eptr);
/* If the result is 0, test for an error */
if (result == 0)
{
/* If the value provided was out of range, display a warning message */
if (errno == ERANGE) printf("The value provided was out of range\n");
}
/* Display the converted result */
printf("%f decimal\n", result);
return 0;
}
958.000000 decimal 2226.000000 decimal