LoginSignup
1
1

More than 3 years have passed since last update.

VC++2012でフォーマット指定子

Last updated at Posted at 2020-07-09

VC2013だったら可変長引数テンプレートを利用してCStringのFormatのようなものを作れたが、Visual C++ 2012では非対応。

調べてみると、stack overflowで使えるものがあったので使いやすく少し修正したものを載せておきます。

https://stackoverflow.com/questions/2342162/stdstring-formatting-like-sprintf/8098080


#include <cstdarg>
#include <memory>
#include <string>

std::string string_format(const std::string fmt_str, ...)
{
    auto n = 256; // 十分なサイズを確保
    std::unique_ptr<char[]> formatted;
    va_list ap;
    while (true)
    {
        formatted.reset(new char[n]);
        strcpy_s(&formatted[0], _TRUNCATE, fmt_str.c_str());
        va_start(ap, fmt_str);
        const auto final_n = _vsnprintf_s(&formatted[0], n, _TRUNCATE, fmt_str.c_str(), ap);
        va_end(ap);
        if (final_n < 0 || final_n >= n)
            n += abs(final_n - n + 1);
        else
            break;
    }
    return std::string(formatted.get());
}

使い方

std::cout << string_format("%d %e %s", 1,1.0/3,"Hello World!") << std::endl;
// 1 3.333333e-001 Hello World!
1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1