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?

c++ format vformatまとめ1

Posted at

#c++ format vformatサンプル

format: コンパイル時書式文字列
vformat: 実行時の書式文字列

#include <iostream>
#include <sstream>
#include <format>
#include <locale>

using namespace std;

//カスタムロケール
class comma_numpunct : public numpunct<char> {
protected:
	virtual char do_decimal_point() const override {
		return ','; 
	}
	virtual char do_thousands_sep() const override {
		return '.'; 
	}
	virtual string do_grouping() const override {
		return "\003";
	}
};

/*
* 最小構成
*/
void format_sample0() {
	cout << format("{}{} {}{}", "Hello", ',', "C++", 0) << endl;

}

/*
* 型明示
*/

void format_sample1() {
	format_string<string_view,char,string,int> fmt = "{}{} {}{}";
	string s1 = format(fmt, string_view("Hello"), ',', string("C++"),1);
	cout << s1 << endl;


}
/**
	型推論は出来ない
	void format_sample1_1() {
	auto fmt = "{}{} {}{}";
	string s1 = format(fmt, string_view("Hello"), ',', string("C++"), 1);
	cout << s1 << endl;

}
*/


/**
ロケール設定あり
*/
void format_sample2(const locale&loc) {
	double d1 = 123456.78901;
	cout << format(loc,"{}\t{:L}", d1,d1) << endl;

}

/******************************************************
	文字フォーマットが実行時に決まる場合
	vformat

************/
template<typename... Args>
void vprintln(const string fmt, Args&&... args)
{
	cout << vformat(fmt, make_format_args(args...)) << endl;
}

/**
最小構成
*/
void vformat_sample1() {
	vprintln("{}{} {}{}", "Hello", ',', "C++", -1 + 2 * 3 * 4);

}


/**
オプション書式
https://cpprefjp.github.io/reference/format/format.html
[[fill] align] [sign] ['#'] ['0'] [width] ['.' precision] ['L'] [type]
*/

int main(){


	format_sample0();
	format_sample1();

	locale loc1("en-US.UTF-8");
	locale loc2(locale::classic(), new comma_numpunct());
	format_sample2(loc1);
	format_sample2(loc2);

	vformat_sample1();
	return 0;
}


0
0
0

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?