IT_컴퓨터_코딩_개발

[fmtlib] Format String Syntax Examples

파워유저 2022. 9. 25. 20:09

참고 : https://fmt.dev/latest/syntax.html

 

Format String Syntax — fmt 9.0.0 documentation

Format String Syntax Formatting functions such as fmt::format() and fmt::print() use the same format string syntax described in this section. Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in b

fmt.dev

 

fmt::print("Hello, {name}! The answer is {number}. Goodbye, {name}.\n", fmt::arg("name", "World"), fmt::arg("number", 42));
//Hello, World! The answer is 42. Goodbye, World.

using namespace fmt::literals;
fmt::print("Hello, {name}! The answer is {number}. Goodbye, {name}.\n", "name"_a = "World", "number"_a = 42);
//Hello, World! The answer is 42. Goodbye, World.

// 소숫점 3자리까지 반올림
float fNum = 123.456789f;
fmt::print("{:.3f}\n", fNum);
//123.457

// +기호
fmt::print("{:+.3f}\n", fNum);
//+123.457

fmt::print("{:-.3f}\n", fNum);
//123.457

// 기호 자리 비워놓기
fmt::print("{: .3f}\n", fNum);
// 123.457

// 전체 자리수 및 소숫점 자리수 지정
double dNum = 123.444789;
fmt::print("{{{:10.3f}}}\n", dNum);
//{   123.445}

double dNum2 = 123.444444;
fmt::print("{{{:010.3f}}}\n", dNum2);
//{000123.444}


// 인덱스 지정
fmt::print("{0:.3f} {1} {0}\n", fNum, dNum);
//123.457 123.444789 123.45679

// 전체 자리수 지정
int iNum = 123456789;
fmt::print("({:10d})\n", iNum);
//( 123456789)
fmt::print("({:010d})\n", iNum);
//(0123456789)

// 왼쪽 정렬
fmt::print("({:<12d})\n", iNum);
//(123456789   )

// 오른쪽 정렬
fmt::print("({:>12d})\n", iNum);
//(   123456789)

// 가운데 정렬(문자 A로 패딩)
fmt::print("({:A^12d})\n", iNum);
//(A123456789AA)


// 2진수 표시
fmt::print("{:b}\n", iNum);
//111010110111100110100010101
fmt::print("{:#b}\n", iNum);
//0b111010110111100110100010101

// 8진수 표시
fmt::print("{:o}\n", iNum);
//726746425
fmt::print("{:#o}\n", iNum);
//0726746425

// 16진수 표시
fmt::print("{:x}\n", iNum);
//75bcd15
fmt::print("{:#x}\n", iNum);
//0x75bcd15

// line
fmt::print(FMT_STRING("{:-^12}\n{: ^12}\n{0:-^12}\n"), "", "Hello!");
//Syntax Error!!!

fmt::print(FMT_STRING("{0:-^12}\n{1: ^12}\n{0:-^12}\n"), "", "Hello!");
//------------
//   Hello!
//------------

std::vector<double> v{ 1.2, 5.6, 7.8 };
fmt::print("{}\n", v);
//[1.2, 5.6, 7.8]

std::map<int, double> m{ {1, 1.1}, {2, 2.2}, {3, 3.3} };
fmt::print("{}\n", m);
//{1: 1.1, 2: 2.2, 3: 3.3}

// DateTime format
auto t = tm();
t.tm_year = 2022 - 1900;
t.tm_mon = 8 - 1;
t.tm_mday = 4;
t.tm_hour = 12;
t.tm_min = 15;
t.tm_sec = 58;
fmt::print("{:%Y-%m-%d %H:%M:%S}\n", t);
//2022-08-04 12:15:58