ulfben icon

Modern C++ printf String formating

ulfben | PRO | 11/23/18 07:25:37 PM UTC | 0 ⭐ | 1039 👁️ | Never ⏰ | []
C++ |

1.89 KB

|

None

|

0 👍

/

0 👎

//Courtesy of https://msdn.microsoft.com/en-us/magazine/dn913181.aspx
// Kenny Kerr
#include <string>
#include <cassert>
using namespace std::literals::string_literals;
 
template <typename T>
T Argument(T value) noexcept {
    return value;
}
template <typename T>
T const * Argument(std::basic_string<T> const & value) noexcept {
    return value.c_str();
}
 
template <typename ... Args>
int StringPrint(char * const buffer, size_t const bufferCount,  
                char const * const format, Args const & ... args) noexcept {
    int const result = snprintf(buffer, bufferCount, format, Argument(args) ...);
    assert(-1 != result);
    return result;
}
template <typename ... Args>
int StringPrint(wchar_t * const buffer, size_t const bufferCount,
                wchar_t const * const format, Args const & ... args) noexcept {
    int const result = swprintf(buffer, bufferCount, format, Argument(args) ...);
    assert(-1 != result);
    return result;
}
template <typename T, typename ... Args>
void Format(std::basic_string<T>& buffer,T const * const format, Args const& ... args){
    size_t const size = StringPrint(&buffer[0], buffer.size() + 1, format, args ...);
    if (size > buffer.size()){
        buffer.resize(size);
        StringPrint(&buffer[0], buffer.size() + 1, format, args ...);
    }else if (size < buffer.size()){
        buffer.resize(size);
    }
}
 
inline std::string ToString(wchar_t const* value){
    std::string result;
    Format(result, "%ls", value);
    return result;
}
inline std::string ToString(double const value, unsigned const precision = 6){
    std::string result;
    Format(result, "%.*f", precision, value);
    return result;
}
 
 
TEST(StringFormat, ConvertWideCharacterToString) {
    ASSERT_TRUE("hello"s == ToString(L"hello"));
}
TEST(StringFormat, ConvertDoubleToString) {
    ASSERT_TRUE("123.46"s == ToString(123.456, 2));
}
TEST(StringFormat, ConvertFloatToString) {
    ASSERT_TRUE("123.457"s == ToString(123.45678f, 3));
}

Comments

  • Gyqizv icon
    04/02/26 06:20:39 PM UTC
    text |

    0 B

    |

    0 👍

    /

    0 👎

    Best t33n active cpx link daily updates!
     Copy and paste the link in a new browser tab and then hit enter!
     https://crazyporn.@xxx/members/157354/?asgtbndr=1&play=true&spon=adworld&zone=400
     Remove the @ 
  • Yuizcko icon
    05/18/26 01:08:17 PM UTC
    text |

    0 B

    |

    0 👍

    /

    0 👎

    Best t33n active cpx link daily updates!
     Copy and paste the link in a new browser tab and then hit enter!
     https://crazyporn.xxx/members/157354/?asgtbndr=1&play=true&spon=adworld&zone=400