std::quoted

std::quoted (따옴표 붙은 삽입·추출 조작자)

문자열을 따옴표로 묶고 escape 처리해 삽입하거나, 따옴표 붙은 문자열을 추출하는 조작자예요. C++14부터 있어요.

출처: cppreference

본문

<iomanip> 헤더에 정의돼 있어요.

// (1) C++14
template< class CharT >
/*unspecified*/ quoted( const CharT* s,
                        CharT delim = CharT('"'), CharT escape = CharT('\\') );

// (2) C++14
template< class CharT, class Traits, class Allocator >
/*unspecified*/ quoted( const std::basic_string<CharT, Traits, Allocator>& s,
                        CharT delim = CharT('"'), CharT escape = CharT('\\') );

// (3) C++14
template< class CharT, class Traits>
/*unspecified*/ quoted( std::basic_string_view<CharT, Traits> s,
                        CharT delim = CharT('"'), CharT escape = CharT('\\') );

out << quoted(s)는 문자열 s를 구분자 delim으로 둘러싸고, escape 문자로 구분자·escape를 이스케이프해 출력해요. in >> quoted(s)는 따옴표 붙은 문자열을 파싱해 s에 저장해요. 기본 구분자는 ", 기본 escape는 \예요. round-trip(출력 후 입력)이 안전하게 유지되는 게 목적이에요.

예제

#include <iostream>
#include <iomanip>
#include <sstream>

int main()
{
    std::ostringstream oss;
    oss << std::quoted("a\"b\\c");           // 따옴표 + 이스케이프
    std::cout << oss.str() << '\n';           // "\"a\\\"b\\\\c\""

    std::istringstream iss(oss.str());
    std::string s;
    iss >> std::quoted(s);                    // 다시 파싱
    std::cout << s << '\n';                   // a"b\c
}

더 알아보기 (Learn more)

cppreference