简体   繁体   English

将CString转换为mfc中的float

[英]Convert CString to float in mfc

how can I convert a CString variable to a floating point? 如何将CString变量转换为浮点数? (I'm using visuall c++ 6.0 and the MFC) (我正在使用visuall c ++ 6.0和MFC)

I'm trying to use an edit box to return a value which I'm putting into an array of floating points. 我正在尝试使用编辑框返回一个值,我将其放入一个浮点数组中。 I'm Using the GetWindowText method to get the value, which returns a CString. 我正在使用GetWindowText方法获取值,该值返回CString。 So I need to convert to a floating point. 所以我需要转换为浮点数。 (or am I just doing things completely the wrong way?). (或者我只是完全以错误的方式做事?)。

I presume there are methods for doing this already in the MFC.(have already used the Format method to convet to a CString display the values in the array in the edit box) 我假设有一些方法可以在MFC中执行此操作。(已经使用Format方法传送到CString,在编辑框中显示数组中的值)

Thanks. 谢谢。

you can just do 你可以这样做

    CString pi = "3.14";
    return atof(pi);

EDIT 编辑

Also use this function: 也可以使用这个功能:

    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. 读取字符串值并将其解析/转换为float允许您在有错误时找到错误。 All you need is a help of a C Run-time function: strtod() or atof(). 您所需要的只是C运行时函数的帮助:strtod()或atof()。

I would prefer strtod as the second argument returns a pointer to the string where the parse terminated: 我更喜欢strtod,因为第二个参数返回指向解析终止的字符串的指针:

 CString str;
m_edtMyEditBox.GetWindowText(str);
char *pEnd;
double dValue = strtod(str.GetBuffer(str.GetLength()), &pEnd);
if (*pEnd != '\0')
{
    // Error in parsing
}
str.ReleaseBuffer();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM