Do C++ formatting libraries generally fall back to *sprintf for numeric formatting?

核能气质少年 提交于 2019-12-07 22:07:07

问题


I am wondering whether "all" C++ formatting libraries eventually fall back to a *sprintf function to format numbers.

I am asking this because:

  • Looking at the iostreams library that comes with Visual C++, I can see that numbers input into a stream will eventuall be formatted with sprintf_s.
  • Boost.Format just uses the available iostreams library as far as I can tell.
  • FastFormat eventually uses vsprintf to format a number.

So, are there iostreams implementations that do not use *sprintf and do the formatting themselves? Are there other formatting libraries that do not forward formatting of numbers to *sprintf family of functions?

I would appreciate answers in the form of:

  • No: implementation XY uses ABC to format numbers
  • Yes: all other (e.g. iostreams) implementations I know (X, Y, Z) also forward number formatting to stdio, because ...

Please avoid overly speculative answers.


回答1:


Boost Spirit doesn't use *printf, as can be seen from the code (real.hpp and int.hpp) and the benchmarks for e.g. ints and doubles.

The benchmark pits Boost Spirit Karma's generators against Boost.Format against sprintf and std::stringstream. Only for gcc compilers does the performance of sprintf come close in that benchmark. Otherwise, Boost Spirit is the clear winner.

  • http://www.boost.org/doc/libs/1_47_0/libs/spirit/doc/html/spirit/karma/performance_measurements/numeric_performance.html



回答2:


No, at least this formatting library has its own implementation of integer formatting. It uses snprintf only for floating-point numbers, but there are plans to use double-conversion for better performance. Currently the performance of this library is close to that of printf according to this benchmark. I wrote this blog post explaining how this was possible without sacrificing type safety.

Note that the benchmarks of Boost Karma are a bit misleading because they compare formatting like printf to double-to-string conversion like dtoa. The difference is that the former gives you more control over output and does more work at runtime to process format specification.

Disclaimer: I'm the author of the mentioned formatting library.



来源:https://stackoverflow.com/questions/7684472/do-c-formatting-libraries-generally-fall-back-to-sprintf-for-numeric-formatti

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