Is there some way to reduce this code?
CString j;
j.Format("%.2f", cardsum);
rep_templ.Replace("%cardsum%", j);
rep_templ.Replace("%cardsum%", CString().Format("%.2f", cardsum))
is not an option, because .Format
is void
.
Is there some way to reduce this code?
CString j;
j.Format("%.2f", cardsum);
rep_templ.Replace("%cardsum%", j);
rep_templ.Replace("%cardsum%", CString().Format("%.2f", cardsum))
is not an option, because .Format
is void
.
2 Answers
Reset to default 0Best way to reduce that code is to use one of the available text template engines such as Inja or Mustache (both results of Google Search, I am not affiliated with either and don't recommend one or the other, just the principle of not rolling your own C++ text template engine).
Here is an implementation of a function that returns a formatted CString
.
I use this in actual production code.
CString FormatString(LPCTSTR pszFormat, ...)
{
ATLASSERT(AtlIsValidString(pszFormat));
CString thestring;
va_list argList;
va_start(argList, pszFormat);
thestring.FormatV(pszFormat, argList);
va_end(argList);
return thestring;
}
You can call it like this:
rep_templ.Replace("%cardsum%", FormatString("%.2f", cardsum));
CString
this cannot be done any more concisely. But you can avoidCString
and usestd::format
instead (starting with C++20). This allows chaining function calls, e.g.,format( ... ).replace( ... );
. – IInspectable Commented Jan 30 at 17:14FormatV
, that returnsCString
. Then you can write something likerep_templ.Replace("%cardsum%", FormatCString("%.2f", cardsum))
– Igor Tandetnik Commented Jan 30 at 23:20