Advertisement
ulfben

Modern C++ printf String formating

Nov 23rd, 2018
436
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. //Courtesy of https://msdn.microsoft.com/en-us/magazine/dn913181.aspx
  2. // Kenny Kerr
  3. #include <string>
  4. #include <cassert>
  5. using namespace std::literals::string_literals;
  6.  
  7. template <typename T>
  8. T Argument(T value) noexcept {
  9.     return value;
  10. }
  11. template <typename T>
  12. T const * Argument(std::basic_string<T> const & value) noexcept {
  13.     return value.c_str();
  14. }
  15.  
  16. template <typename ... Args>
  17. int StringPrint(char * const buffer, size_t const bufferCount, 
  18.                 char const * const format, Args const & ... args) noexcept {
  19.     int const result = snprintf(buffer, bufferCount, format, Argument(args) ...);
  20.     assert(-1 != result);
  21.     return result;
  22. }
  23. template <typename ... Args>
  24. int StringPrint(wchar_t * const buffer, size_t const bufferCount,
  25.                 wchar_t const * const format, Args const & ... args) noexcept {
  26.     int const result = swprintf(buffer, bufferCount, format, Argument(args) ...);
  27.     assert(-1 != result);
  28.     return result;
  29. }
  30. template <typename T, typename ... Args>
  31. void Format(std::basic_string<T>& buffer,T const * const format, Args const& ... args){
  32.     size_t const size = StringPrint(&buffer[0], buffer.size() + 1, format, args ...);
  33.     if (size > buffer.size()){
  34.         buffer.resize(size);
  35.         StringPrint(&buffer[0], buffer.size() + 1, format, args ...);
  36.     }else if (size < buffer.size()){
  37.         buffer.resize(size);
  38.     }
  39. }
  40.  
  41. inline std::string ToString(wchar_t const* value){
  42.     std::string result;
  43.     Format(result, "%ls", value);
  44.     return result;
  45. }
  46. inline std::string ToString(double const value, unsigned const precision = 6){
  47.     std::string result;
  48.     Format(result, "%.*f", precision, value);
  49.     return result;
  50. }
  51.  
  52.  
  53. TEST(StringFormat, ConvertWideCharacterToString) {
  54.     ASSERT_TRUE("hello"s == ToString(L"hello"));
  55. }
  56. TEST(StringFormat, ConvertDoubleToString) {
  57.     ASSERT_TRUE("123.46"s == ToString(123.456, 2));
  58. }
  59. TEST(StringFormat, ConvertFloatToString) {
  60.     ASSERT_TRUE("123.457"s == ToString(123.45678f, 3));
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement