c++atlc-str

format float in C++ mfc


I used VS2010 to build a MFC program in windows 7. I want to format the float data in the report generated.

I have tried to use %f but the "%f" is showed in the report.

CString m_Iwork_min;
struct   m_report_info;
m_Iwork_min = ......;
......
m_report_info.Iwork = "Pass, %f, %f, %f", atof(m_Iwork_min), 
atof(m_Iwork_max), atof(Value[0].c_str());

Expected results:

Pass, 1.2, 3.4, 5.67

Actual results:

Pass, %f, %f, %f


Solution

  • It doesn't fill in a format string on its own, you have to call a function to do so. snprintf can be used for this, but in your case, you're probably looking for CString::Format. It's hard to say what's going on in your code because there's no MCVE, so I did some assumptions and got the following to run:

    #include <tchar.h>
    #include <atlstr.h>
    #include <string>
    
    int main()
    {
        CString m_Iwork_min = "1.2";
        CString m_Iwork_max = "3.4";
        std::string Value[] = { "5.67", "foo", "bar" };
        CString Iwork;
        Iwork.Format(_T("Pass, %lf, %lf, %lf"), _tstof(m_Iwork_min),
            _tstof(m_Iwork_max), atof(Value[0].c_str()));
        _tprintf(_T("%s"), (LPCTSTR)Iwork);
        return 0;
    }
    

    Output:

    Pass, 1.200000, 3.400000, 5.670000

    The c_str in your code makes it look like you want a mix of CString and std::string. Is this really what you intended? Make sure to always include a Minimal, Complete, and Verifiable example in your questions, they make it easier to help you.