title: Convert wstring to string encoded in UTF-8
body: <p>I need to convert between wstring and string. I figured out, that using codecvt facet should do the trick, but it doesn't seem to work for utf-8 locale.</p>
  
  <p>My idea is, that when I read utf-8 encoded file to chars, one utf-8 character is read into two normal characters (which is how utf-8 works). I'd like to create this utf-8 string from wstring representation for library I use in my code.</p>
  
  <p>Does anybody know how to do it?</p>
  
  <p>I already tried this:</p>
  
  <pre><code>  locale mylocale("cs_CZ.utf-8");
    mbstate_t mystate;
  
    wstring mywstring = L"čřžýáí";
  
    const codecvt&lt;wchar_t,char,mbstate_t&gt;&amp; myfacet =
      use_facet&lt;codecvt&lt;wchar_t,char,mbstate_t&gt; &gt;(mylocale);
  
    codecvt&lt;wchar_t,char,mbstate_t&gt;::result myresult;  
  
    size_t length = mywstring.length();
    char* pstr= new char [length+1];
  
    const wchar_t* pwc;
    char* pc;
  
    // translate characters:
    myresult = myfacet.out (mystate,
        mywstring.c_str(), mywstring.c_str()+length+1, pwc,
        pstr, pstr+length+1, pc);
  
    if ( myresult == codecvt&lt;wchar_t,char,mbstate_t&gt;::ok )
     cout &lt;&lt; "Translation successful: " &lt;&lt; pstr &lt;&lt; endl;
    else cout &lt;&lt; "failed" &lt;&lt; endl;
    return 0;
  </code></pre>
  
  <p>which returns 'failed' for cs_CZ.utf-8 locale and works correctly for cs_CZ.iso8859-2 locale.</p>