컴퓨터 언어/C++

std::string 으로 format 구현

cepiloth 2021. 4. 29. 16:31
728x90

구현부

template<typename ... Args> 
std::string string_format(const std::string& format, Args ... args)
{
	size_t size = snprintf(nullptr, 0, format.c_str(), args ...) + 1; // Extra space for '\0' 
	if (size <= 0) {
		throw std::runtime_error("Error during formatting.");
	}
	std::unique_ptr<char[]> buf(new char[size]);
	snprintf(buf.get(), size, format.c_str(), args ...);
	return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside }
}

 

사용법

std::string save_path = string_format("d:\\test%d.tif", count++);

 

https://gist.github.com/kuonzZ/14c0ee6a21950f8b46f50ae7053c0873

 

728x90
반응형