Reading UTF-8 data with C++ in Mac not working
<p>Although my C++ experience is quite reduced, I am trying to help a C++ programmer to have his library working on a Mac. At the moment, the problem seems to be only locale/encoding related.</p>

<p>Trying to create a minimal working example, I tested the following code, that reads a line of UTF-8 Characters, to a wide string (wstring) and then goes through the string and prints each character.</p>

<p>While it works perfectly on a Linux box, having all characters printed in a different line, when using a Mac box I get each <strong>byte</strong> printed per line (and not each character).</p>

<p>The code is:</p>

<pre><code>#include &lt;sstream&gt;
#include &lt;iostream&gt; 
#include &lt;string&gt;
#include &lt;boost/locale.hpp&gt;

using namespace std;

int main() {
    std::ios_base::sync_with_stdio(false);
    boost::locale::generator gen;
    locale mylocale = gen("pt_PT.UTF-8");
    locale::global(mylocale);

    wstring userInput;
    getline(wcin, userInput);

    wcerr &lt;&lt; "Size of string is " &lt;&lt; userInput.length() &lt;&lt; endl;

    for (int i = 0; i &lt; userInput.length(); ++i) {
        wcerr &lt;&lt; userInput.at(i) &lt;&lt; endl;
    }
    return 0;
}
</code></pre>

<p>and my testing string is a stupid Portuguese sentence:</p>

<pre><code>O coração é um órgão frágil.
</code></pre>

<p>I am trying with Boost_locale because somebody told me it was he way to get unicode working correctly on a Mac, but I would be happy to have a solution using only the C++ standard libraries.</p>

<p><strong>EDIT:</strong></p>

<p>The following code works on Mac. It doesn't compile on my Linux box because of the codecvt include, but I can manage that with some CPP instructions.</p>

<pre><code>#include &lt;sstream&gt;
#include &lt;iostream&gt; 
#include &lt;fstream&gt;
#include &lt;codecvt&gt;
#include &lt;locale&gt;
#include &lt;string&gt;

using namespace std;

int main() {
    // setting std::local::global seems not to work (??)

    wcin.imbue(std::locale(locale(""), new std::codecvt_utf8&lt;wchar_t&gt;));
    wcerr.imbue(std::locale(locale(""), new std::codecvt_utf8&lt;wchar_t&gt;));

    wstring userInput;
    getline(wcin, userInput);

    wcerr &lt;&lt; "Size of string is " &lt;&lt; userInput.length() &lt;&lt; endl;

    for (int i = 0; i &lt; userInput.length(); ++i) {
        wcerr &lt;&lt; userInput.at(i) &lt;&lt; endl;
    }
    return 0;
}
</code></pre>