C++ 在 mfc 中将 CString 转换为浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5788772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:53:04  来源:igfitidea点击:

Convert CString to float in mfc

c++visual-c++mfc

提问by karthik

how can I convert a CString variable to a floating point? (I'm using visuall c++ 6.0 and the MFC)

如何将 CString 变量转换为浮点数?(我使用的是 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. So I need to convert to a floating point. (or am I just doing things completely the wrong way?).

我正在尝试使用编辑框返回一个值,我将其放入浮点数组中。我正在使用 GetWindowText 方法来获取返回 CString 的值。所以我需要转换为浮点数。(或者我只是完全以错误的方式做事?)。

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.

谢谢。

回答by karthik

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. 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 != '##代码##')
{
    // Error in parsing
}
str.ReleaseBuffer();