【问题标题】:mfc - float to string, storing it in file and read it from filemfc - 浮动到字符串,将其存储在文件中并从文件中读取
【发布时间】:2015-01-15 14:48:03
【问题描述】:

我正在使用 Visual Studio 2010 创建 MFC 应用程序。 我必须使用带有 2 个编辑控件的对话框,输入编辑控件的值我必须添加并在屏幕上打印,例如:“Addend1 + Addend2 = Result”。 现在,我使用 _ttof() 函数从字符串中获取浮点数,添加两个值后,我使用哪个函数从浮点数中获取字符串? 而且,在那之后,我将不得不将它存储在文件中并阅读它。我是这样做的:

void CseminarskiDoc::Serialize(CArchive& ar)

{

if (ar.IsStoring())
{
    // TODO: add storing code here
    ar << m_text;
}
else
{

    // TODO: add loading code here

    ar >> m_text;

}

}

这行“ar>> m_text”是否意味着存储到文件中的值将被读入m_text并显示在屏幕上?我可以这样做吗

ar>>m_text1>> "+" >>m_text2>> "=" >>m_text;

有像“Addend1 + Addend2 = Result”这样的输出?

在 ExView.cpp 文件中,我是否必须添加一些行来执行输出,或者最后一个命令可以是执行 float-> string 的函数?

对不起,我的英语不好:D

谢谢你:D

【问题讨论】:

    标签: string file mfc output


    【解决方案1】:

    你做错了!

    不要在对话框中使用文本或 CString 变量。而是定义浮点或双精度变量。我猜你正在使用浮点数......

    // members of class CZBroj in your ZBroj.h
    
    float m_fVar1;
    float m_fVar2;
    
    void CZBroj::DoDataExchange(CDataExchange* pDX)
    {
       CDialog::DoDataExchange(pDX);
       DDX_Text(pDX, IDC_EDIT1, m_fVar1); // if not IDC_EDIT1, change to correct ID
       DDX_Text(pDX, IDC_EDIT2, m_fVar2);
    }
    
     void CseminarskiView::OnEditZbroj()
    {
       CseminarskiDoc* pDoc = GetDocument();
       CZbroj dlg; // deklariranje dijaloga
       dlg.m_fVar1 = 3.4; //use whatever value you want to initialize with
       dlg.m_fVar2 = 1.414; // again, init with whatever you want, or be sure to init in constructor
       if (IDOK == dlg.DoModal())
       {
           // respond appropriately
           // dlg.m_fVar1,dlg.m_fVar2 will contain the edited values...magic of DDX_Text
       }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用这样的代码将浮点数转换为字符串:

      CString s;
      s.Format(_T("%f"), floatvariable);
      

      它也可以用来构建你想要的输出字符串:

      s.Format(_T("%f + %f = %f"), Addend1, Addend2, Result);
      

      CArchive 内容不显示任何内容,也不连接字符串。事实上,CArchive 不会创建一个普通的文本文件,因此它可能根本不适合您想要的文件。

      【讨论】:

        猜你喜欢
        • 2014-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-08
        • 2020-08-11
        • 1970-01-01
        • 2013-04-08
        相关资源
        最近更新 更多