0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C++でフォーマット文字列を生成する関数

Last updated at Posted at 2023-01-18

概要

Goのfmt.Sprintf関数のようなフォーマット文字列を生成する関数をC++で使用したかったが,std::string型でフォーマット文字列を生成する関数がC++17まではなさそうだったので自作した.

なお,Boostライブラリを使用できる環境か,あるいはC++20以降なら以下の関数は不要である.それぞれ,boost::format()関数,std::format関数を使用できる.

ソースコード

main.cpp
#include <cstdarg>

#include <iostream>
#include <string>

/**
 * @brief 1023文字(+ヌル文字)までの文字列をフォーマットして返す
 */
std::string StrFormat(const char* format, ...) {
  va_list args;
  va_start(args, format);

  char buffer[1024];
  vsnprintf(buffer, sizeof(buffer), format, args);
  va_end(args);

  return std::string(buffer);
}

int main(int argc, char const* argv[]) {
  std::cout << StrFormat("Hello %s", "World") << std::endl;
  return 0;
}
0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?