C++14 quotedマニピュレータ

N3654 Quoted Strings Library Proposal (Revision 2)


CSVXMLといったフォーマットでは、ダブルクォーテーションで囲まれた文字列を扱う必要がありますが、C++の入出力ライブラリには、このようなものを直接的にサポートする機能がありませんでした。
このような状況のために、C++14ではヘッダにquotedマニピュレータが追加されます。


quotedマニピュレータによって出力された文字列は、デフォルトでダブルクォーテーションによって囲まれます。

#include <iostream>
#include <iomanip>
#include <string>

int main()
{
    std::string s = "hello";
    std::cout << std::quoted(s) << std::endl;
}
"hello" 

逆に、読み込み時にquotedマニピュレータを使用すれば、ダブルクォーテーションで囲まれた文字列を読み込めます。

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

int main()
{
    std::string s;

    std::stringstream ss;
    ss << "\"hello\"";
    ss >> std::quoted(s);

    std::cout << s << std::endl;
}
hello

また、「hello world」のようなスペースの入った文字列をストリームで読み込もうとすると、一度の文字列読み込みでは「hello」しか読み込めませんが、ダブルクォーテーションで囲んでquotedマニピュレータ付きで読み込めば、「hello world」全部が読み込めます。

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

int main()
{
    std::string s;

    std::stringstream ss;
    ss << "\"hello world\"";
    ss >> std::quoted(s);

    std::cout << s << std::endl;
}
hello world 


quotedマニピュレータは、以下のように宣言されます。

// <iomanip>
namespace std {
  template <class charT>
  T11 quoted(const charT* s, charT delim=charT('"'), charT escape=charT('\\'));

  template <class charT, class traits, class Allocator>
  T12 quoted(const basic_string<charT, traits, Allocator>& s,
             charT delim=charT('"'), charT escape=charT('\\'));

  template <class charT, class traits, class Allocator>
  T13 quoted(basic_string<charT, traits, Allocator>& s,
             charT delim=charT('"'), charT escape=charT('\\'));
}