1

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

Blaze
  • 16,736
  • 2
  • 25
  • 44
Bill
  • 33
  • 7
  • Pretty sure that should be `m_report_info.Iwork.Format("Pass, %f, %f, %f", atof(m_Iwork_min), atof(m_Iwork_max), atof(Value[0].c_str()),` – john Feb 18 '19 at 10:40

1 Answers1

1

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.

Blaze
  • 16,736
  • 2
  • 25
  • 44
  • 1
    Yes, pick one string class and stick to it, and since `std::string` is clearly superior to `CString` ... – john Feb 18 '19 at 10:42
  • I also agree that `std::string` is superior. Developers are much more familiar with it, and it's cross-platform. When people use `CString` I assume it's because they have to, for whatever reasons. – Blaze Feb 18 '19 at 10:43
  • `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);` WHAO! This is a mouthful. Hope to never see that in a code review. (nice answer BTW ;) – YSC Feb 18 '19 at 10:56