C++20中头文件format的使用

      是C++20中新增加的头文件,提供字符串格式化功能,此头文件是format库的一部分。包括:

      1.classes:

      std::formatter:为给定类型定义格式规则。

      std::basic_format_parse_context、std::format_parse_context、std::std::wformat_parse_context:提供对格式字符串解析状态的访问。

      std::format_error:格式错误时抛出的异常类型。

      2.functions:

      std::format:将参数的格式化表示存储在新字符串中。

      std::format_to:通过输出迭代器写出其参数的格式化表示。

      std::format_to_n:通过输出迭代器写出其参数的格式化表示,不超过指定的大小。

      std::formatted_size:确定存储其参数的格式化表示所需的字符数。

      std::vformat:std::format的非模板变体,接受一个std::format_args对象。

      std::vformat_to:std::format_to 的非模板变体,接受一个std::format_args对象。

      以下为测试代码:

int test_format_functions()
{
	constexpr auto value{ 66.6666f };
	constexpr auto name{ "Tom" };

	// std::format
	auto ret = std::format("Name is {}, value is {}", name, value);
	std::cout << ret << std::endl; // Name is Tom, value is 66.6666

	ret = std::format("Name is {1}, value is {0}", value, name);
	std::cout << ret << std::endl; // Name is Tom, value is 66.6666

	ret = std::format("Name is {1:.2s}, value is {0:.2f}", value, name);
	std::cout << ret << std::endl; // Name is To, value is 66.67

	// std::format_to
	std::string buffer;
	std::format_to(std::back_inserter(buffer), "Name is {1:.2s}, value is {0:.2f}", value, name);
	std::cout << buffer << std::endl; // Name is To, value is 66.67

	// std::format_to_n
	constexpr int length{ 16 };
	std::array buf;
	//std::memset(buf.data(), 0, buf.size());
	const std::format_to_n_result result = std::format_to_n(buf.data(), buf.size()-1, "Name is {1:.2s}, value is {0:.2f}", value, name);
	*result.out = '\0'; // adds terminator to buf, no longer required: std::memset(buf.data(), 0, buf.size());
	std::cout << "untruncated output size: " << result.size << ",result: " << buf.data() << std::endl; // untruncated output size: 26,result: Name is To, val

	// std::formatted_size
	const auto required_size{ std::formatted_size(name, value) }; // the result is incorrect, why?
	std::cout << required_size << std::endl; // 3

	// std::vformat
	std::string_view strv{ "Name is {1:.2s}, value is {0:.2f}" };
	auto args_fmt = std::make_format_args(value, name);
	ret = std::vformat(strv, args_fmt);
	std::cout << ret << std::endl; // Name is To, value is 66.67

	// std::vformat_to
	std::string buf2;
	std::vformat_to(std::back_inserter(buf2), strv, args_fmt);
	std::cout << buf2 << std::endl; // Name is To, value is 66.67

	// std::format_error
	try {
		std::string_view strv{ "Name is {1:.2s}, value is {0:.2f}" };
		auto args_fmt = std::make_format_args(name, value);
		ret = std::vformat(strv, args_fmt);
	}
	catch (const std::format_error& ex) {
		std::cout << "error info: " << ex.what() << std::endl; // error info: Invalid presentation type for floating-point
	}

	return 0;
}

      执行结果如下图所示:

C++20中头文件format的使用_第1张图片

      GitHub:https://github.com/fengbingchun/Messy_Test

你可能感兴趣的:(C++20,format)