https://fmt.dev/latest/index.html

 

Overview — fmt 9.1.0 documentation

Overview {fmt} is an open-source formatting library providing a fast and safe alternative to C stdio and C++ iostreams. What users say: Thanks for creating this library. It’s been a hole in C++ for a long time. I’ve used both boost::format and loki::SP

fmt.dev

fmt 라는 문자열 format 라이브러리가 있다. 헤더만 추가하고 FMT_HEADER_ONLY 만 선언해줘도 사용 가능해서 사용하기 편하다.

https://en.cppreference.com/w/cpp/utility/format

 

Formatting library (since C++20) - cppreference.com

The text formatting library offers a safe and extensible alternative to the printf family of functions. It is intended to complement the existing C++ I/O streams library. [edit] Formatting functions stores formatted representation of the arguments in a new

en.cppreference.com

#include <cassert>
#include <format>
 
int main()
{
    std::string message = std::format("The answer is {}.", 42);
    assert( message == "The answer is 42." );
}

c++ 20 부터 추가된 formatting 라이브러리를 사용하면 되는데 printf format specifier 인 % 구문이 아니라 {} 를 사용한다. 형식을 지정하지 않아도 되서 형식 지정 오류를 줄일 수 있다.

void f_withoutFmt()
{
	std::vector<int> items { 0, 1, 2, 3 };
	
	bool bFirst = true;
	
	std::string str;
	for (const auto& item : items)
	{
		if (! bFirst)
		{
			str.append(",");
		}
		str.append(std::to_string(item));
		bFirst = false;
	}
	
	std::cout << "items1 : " << str << std::endl;
}

vector 형식의 아이템들을 출력할 때 루프를 돌면서 문자열을 추가해주는 식으로 코드를 짜게 된다. 쓸데없이 길다.

void f_withFmt()
{
	std::vector<int> items { 0, 1, 2, 3 };
	
	std::cout << "items2 : " << fmt::format("{}", fmt::join(items, ",")) << std::endl;
}

fmt::join 을 이용할 경우 간결해진다.

https://stackoverflow.com/questions/59280481/convert-a-vectorint-to-string-with-fmt-library

 

Convert a vector<int> to string with fmt library

How to remove {} from the output? #include <iostream> #include <vector> #include <fmt/format.h> #include <fmt/ranges.h> int main () { std::vector<int> v = {1,2,3}...

stackoverflow.com

 

728x90

+ Recent posts