Skip to content

Instantly share code, notes, and snippets.

@bathoryr
Created June 12, 2018 20:19
Show Gist options
  • Select an option

  • Save bathoryr/56f2c78d6f0016630a1ba80e4aee9c4f to your computer and use it in GitHub Desktop.

Select an option

Save bathoryr/56f2c78d6f0016630a1ba80e4aee9c4f to your computer and use it in GitHub Desktop.
Format string in modern C++
#pragma once
#include <memory>
#include <iostream>
#include <string>
#include <cstdio>
template<typename ... Args>
std::wstring string_format(const std::wstring& format, Args ... args)
{
size_t size = std::swprintf(nullptr, 0, format.c_str(), args ...) + 1; // Extra space for '\0'
std::unique_ptr<WCHAR[]> buf(new WCHAR[size]);
std::swprintf(buf.get(), size, format.c_str(), args ...);
return std::wstring(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment