最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

visual c++ - How can I reduce my code using CString::Format - Stack Overflow

programmeradmin1浏览0评论

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.

Share Improve this question edited Jan 31 at 7:54 Jabberwocky 50.9k18 gold badges68 silver badges124 bronze badges asked Jan 30 at 16:29 Сергей СоколовСергей Соколов 3754 silver badges16 bronze badges 7
  • Using CString this cannot be done any more concisely. But you can avoid CString and use std::format instead (starting with C++20). This allows chaining function calls, e.g., format( ... ).replace( ... );. – IInspectable Commented Jan 30 at 17:14
  • 1 Write a helper function, based on FormatV, that returns CString. Then you can write something like rep_templ.Replace("%cardsum%", FormatCString("%.2f", cardsum)) – Igor Tandetnik Commented Jan 30 at 23:20
  • 1 Is there any specific reason why you are rolling your own text template engine? – Igor Levicki Commented Jan 31 at 1:29
  • @IgorLevicki which text template engine would you suggest? – Jabberwocky Commented Jan 31 at 7:55
  • 1 @Jabberwocky This one seems very capable github/pantor/inja, and I am sure you can Google for others. – Igor Levicki Commented Feb 3 at 12:04
 |  Show 2 more comments

2 Answers 2

Reset to default 0

Best 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));
发布评论

评论列表(0)

  1. 暂无评论