format_to_n
format_to_n (출력 크기를 제한하는 서식화 함수)
std::format_to_n은 서식 문자열 fmt에 따라 인자들을 서식화하고, 그 결과를 출력 반복자 out에 최대 n개의 문자만 기록하는 함수예요. C++20에서 도입된 <format> 라이브러리의 일부로, 출력 버퍼의 크기를 제한하면서도 전체(잘리지 않은) 출력 크기를 함께 알 수 있어요. std::format이 새 문자열을 통째로 만드는 것과 달리, 이 함수는 사용자가 지정한 버퍼에 직접 쓰므로 메모리 제어가 중요한 상황에서 유용해요.
출처: cppreference
본문
개요
<format> 헤더에 정의되어 있어요.
| Defined in header |
||
|---|---|---|
| template < class OutputIt , class ... Args > std :: format_to_n_result < OutputIt > format_to_n ( OutputIt out , std :: iter_difference_t < OutputIt > n , std :: format_string < Args ... > fmt , Args && ... args ); | (1) | (since C++20) |
| template < class OutputIt , class ... Args > std :: format_to_n_result < OutputIt > format_to_n ( OutputIt out , std :: iter_difference_t < OutputIt > n , std :: wformat_string < Args ... > fmt , Args && ... args ); | (2) | (since C++20) |
| template < class OutputIt , class ... Args > std :: format_to_n_result < OutputIt > format_to_n ( OutputIt out , std :: iter_difference_t < OutputIt > n , const std :: locale & loc , std :: format_string < Args ... > fmt , Args && ... args ); | (3) | (since C++20) |
| template < class OutputIt , class ... Args > std :: format_to_n_result < OutputIt > format_to_n ( OutputIt out , std :: iter_difference_t < OutputIt > n , const std :: locale & loc , std :: wformat_string < Args ... > fmt , Args && ... args ); | (4) | (since C++20) |
| Helper types | ||
| template < class OutputIt > struct format_to_n_result { OutputIt out ; std :: iter_difference_t < OutputIt > size ; }; | (5) | (since C++20) |
서식 문자열 fmt에 따라 인자를 서식화하고, 결과를 출력 반복자 out에 써요. 최대 n개의 문자만 기록되며, loc이 제공되면 로케일별 서식화에 사용돼요.
CharT는 오버로드 (1,3)에서 char, 오버로드 (2,4)에서 wchar_t예요.
이 오버로드들은 OutputIt이 std::output_iterator<const CharT&> 개념을 만족할 때만 오버로드 해석에 참여해요.
OutputIt이 std::output_iterator<const CharT&> 개념을 모델링하지 않거나, Args의 어떤 Ti에 대해서도 std::formatter<std::remove_cvref_t<Ti>, CharT>가 BasicFormatter 요구 사항을 충족하지 않으면 동작이 정의되지 않아요.
매개변수
| 매개변수 | 설명 |
|---|---|
out |
출력 버퍼를 가리키는 반복자 |
n |
버퍼에 기록할 최대 문자 수 |
fmt |
서식 문자열을 나타내는 객체. 서식 문자열은 출력에 그대로 복사되는 일반 문자({와 } 제외), 각각 {와 }로 치환되는 이스케이프 시퀀스 {{와 }}, 그리고 치환 필드로 구성돼요. 각 치환 필드는 다음 형식을 가져요: { arg-id (optional) } (1) 또는 { arg-id (optional) : format-spec } (2). |
arg-id |
서식화에 사용할 args의 인자 인덱스를 지정해요. 생략하면 인자가 순서대로 사용돼요. 서식 문자열의 arg-id는 모두 있거나 모두 생략되어야 해요. 수동 인덱싱과 자동 인덱싱을 섞으면 오류예요. |
format-spec |
해당 인자에 대한 std::formatter 특수화로 정의된 서식 지정이에요. }로 시작할 수 없어요. 기본 타입과 표준 문자열 타입은 표준 서식 지정으로, chrono 타입은 chrono 서식 지정으로, 범위 타입은 범위 서식 지정으로, std::pair와 std::tuple은 튜플 서식 지정으로 해석돼요. std::thread::id와 std::stacktrace_entry는 각각 thread id 서식 지정과 stacktrace entry 서식 지정을 참고하세요. std::basic_stacktrace에는 서식 지정자를 사용할 수 없어요. (C++23부터) std::filesystem::path는 path 서식 지정을 참고하세요. (C++26부터) 다른 서식화 가능 타입은 사용자 정의 formatter 특수화에 따라 결정돼요. |
args... |
서식화할 인자들 |
loc |
로케일별 서식화에 사용되는 std::locale |
반환값
out 멤버가 출력 범위의 끝을 가리키는 반복자이고, size 멤버가 전체(잘리지 않은) 출력 크기인 format_to_n_result를 반환해요.
예외
formatter 또는 반복자 연산이 던지는 모든 예외를 전파해요.
참고
GCC-13.3 이전의 libstdc++ 구현에는 올바른 format_to_n_result::out 값을 보고하지 않는 버그가 있었어요.
예제
Godbolt's Compiler Explorer에서: clang (trunk) + libc++, GCC (trunk) + libstdc++.
#include <format>
#include <initializer_list>
#include <iomanip>
#include <iostream>
#include <string_view>
int main()
{
char buffer[64];
for (std::size_t max_chars_to_write : {std::size(buffer) - 1, 23uz, 21uz})
{
const std::format_to_n_result result =
std::format_to_n(
buffer, max_chars_to_write,
"Hubble's H{2} {3} {0}{4}{1} km/sec/Mpc.", // 24 bytes w/o formatters
71, // {0}, occupies 2 bytes
8, // {1}, occupies 1 byte
"\u2080", // {2}, occupies 3 bytes, '₀' (SUBSCRIPT ZERO)
"\u2245", // {3}, occupies 3 bytes, '≅' (APPROXIMATELY EQUAL TO)
"\u00B1" // {4}, occupies 2 bytes, '±' (PLUS-MINUS SIGN)
); // 24 + 2 + 1 + 3 + 3 + 2 == 35, no trailing '\0'
*result.out = '\0'; // adds terminator to buffer
const std::string_view str(buffer, result.out);
std::cout << "Buffer until '\\0': " << std::quoted(str) << '\n'
<< "Max chars to write: " << max_chars_to_write << '\n'
<< "result.out offset: " << result.out - buffer << '\n'
<< "Untruncated output size: " << result.size << "\n\n";
}
}
출력:
Buffer until '\0': "Hubble's H₀ ≅ 71±8 km/sec/Mpc."
Max chars to write: 63
result.out offset: 35
Untruncated output size: 35
Buffer until '\0': "Hubble's H₀ ≅ 71±8"
Max chars to write: 23
result.out offset: 23
Untruncated output size: 35
Buffer until '\0': "Hubble's H₀ ≅ 71�"
Max chars to write: 21
result.out offset: 21
Untruncated output size: 35
결함 보고
다음 동작 변경 결함 보고서는 이전에 발표된 C++ 표준에 소급 적용되었어요.
| DR | 적용 대상 | 발표된 동작 | 올바른 동작 |
|---|---|---|---|
| P2216R3 | C++20 | 잘못된 서식 문자열에 대해 std::format_error를 던짐 |
잘못된 서식 문자열은 컴파일 타임 오류를 발생시킴 |
| P2418R2 | C++20 | const 사용도 복사도 불가능한 객체(제너레이터 유사 객체)는 서식화할 수 없음 | 이러한 객체의 서식화를 허용 |
| P2508R1 | C++20 | 이 기능에 사용자에게 보이는 이름이 없음 | basic_format_string 이름이 노출됨 |
같이 보기
format (C++20) |
인자의 서식화된 표현을 새 문자열에 저장 (함수 템플릿) [편집] |
|---|---|
format_to (C++20) |
출력 반복자를 통해 인자의 서식화된 표현을 기록 (함수 템플릿) [편집] |
formatted_size (C++20) |
인자의 서식화된 표현을 저장하는 데 필요한 문자 수를 결정 (함수 템플릿) [편집] |