C++ Runtime string formatting

拈花ヽ惹草 提交于 2019-12-25 01:50:05

问题


Usually I use streams for formatting stuff however in this case ?I don't know the format until runtime.

I want to be able to take something like the following format string:
Hello {0}! Your last login was on {1,date:dd/mm/yy}.
...and feed in the variables "Fire Lancer" and 1247859223, and end up with the following formatted string:
Hello Fire Lancer! Your last login was on 17/07/09.

In other languages I use there is built in support for this kind of thing, eg pythons format string method, however in c++ there doesn't seem to be any such functionality, accept the C print methods which are not very safe.

Also this is for a high performance program, so whatever solution I use needs to parse the format string once and store it (eg mayby a Parse method that returns a FormatString object with a Format(string) method), not reparse the string every time the format method is called...


回答1:


Your format string looks very much like those used in ICU MessageFormat. Did you consider using it?




回答2:


Boost Formatting does that for you:

http://www.boost.org/doc/libs/1_39_0/libs/format/doc/format.html

Check out this question and answer for examples of usage:




回答3:


boost::format will do the positional arguments portion, but not the date formatting...



来源:https://stackoverflow.com/questions/1145273/c-runtime-string-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!