how to transfer Cstring to float
-
How to transfer Cstring type like : 6.591E+02 to float type. exmple : Cstring a="6.591E+02"; float b; and i want b=6.591E+02.I work with MFC.Thanks.
-
-
I also used atof(),but with atof() parameter in atof()function is char * but my string is Cstring.:(
If you're doing a Unicode build, you could use
_ttof()
and otherwiseatof()
will work. For example, this code will work for an MBCS build:double df = 0;
CString str = "6.591E+02";
df = atof(str);Hint:
CString
has theLPCTSTR
operator defined, so the conversion will be done automatically."Real men drive manual transmission" - Rajesh.
-
I also used atof(),but with atof() parameter in atof()function is char * but my string is Cstring.:(
Let your variable is
CString strFloat;
then use atof as
atof(strFloat.GetBuffer());
-
Let your variable is
CString strFloat;
then use atof as
atof(strFloat.GetBuffer());
That's a misuse of
CString::GetBuffer()
."Real men drive manual transmission" - Rajesh.
-
How to transfer Cstring type like : 6.591E+02 to float type. exmple : Cstring a="6.591E+02"; float b; and i want b=6.591E+02.I work with MFC.Thanks.
-
I also used atof(),but with atof() parameter in atof()function is char * but my string is Cstring.:(
camuoi288 wrote:
atof() parameter in atof()function is char * but my string is Cstring
That is not correct. From MSDN:
double atof(const char \*string);
Since CString has LPCTSTR operator, you can easily call atof like this:
CString str = "1.234"; double d = atof(str);
Best wishes, Hans
-
How to transfer Cstring type like : 6.591E+02 to float type. exmple : Cstring a="6.591E+02"; float b; and i want b=6.591E+02.I work with MFC.Thanks.
Since you're using C++ I suggest using streams.
#include <sstream>
{
CString strFloat("3.5");
istringstream is(strFloat);
float myFloat;
is >> myFloat;
}This way you can catch errors easily. Consider the following:
float af = atof("a");
float zerof = atof("0");Both af and zerof will be 0, since on error atof() will return 0. Using streams you can check the stream status after conversion:
{
CString strFloat("3.5");
istringstream is(strFloat);
float myFloat;
is >> myFloat;
if (is.fail())
{
// Conversion failed!
}
}