2

I try to run the code blow in Xcode 4.2:

int main(int argc, const char * argv[])
{
    locale loc("chs");
    locale::global(loc);

    wstring text(L"你好");
    wcout << text << endl;
    return 0;
}

I got a error "Thread 1:signal SIGABRT".

Can you Tell me why the error happen or how to use wstring and wcout to output the Chinese words?

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
Sid Zhang
  • 972
  • 3
  • 9
  • 18

2 Answers2

6

You don't. Mac, like other Unix systems, uses UTF8 while Windows uses "Unicode" (UTF-16).

You can print that perfectly well on Mac by using string and cout instead of wstring and wcout.

ADDENDUM

This sample works great. Compile with g++ and run as-is.

#include <string>
#include <iostream>

using namespace std;

int main(int arg, char **argv)
{
    string text("汉语");
    cout << text << endl;

    return 0;
}
Mahmoud Al-Qudsi
  • 28,357
  • 12
  • 85
  • 125
1

The crash is coming from the call to locale(). This SO answer seems related.

As mentioned by Mahmoud Al-Qudsi, you don't need it as you can use UTF-8 in a normal string object:

#include <string>
#include <iostream>

using namespace std;

int main(int argc, const char * argv[])
{

    string text("你好");
    cout<<text<<endl;
    return 0;
}

Produces:

$ ./test
你好

EDIT: Oops, too late :)

Community
  • 1
  • 1
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • Our development team gave up on using locale management on OS X. OS X (unlike all the other OSes out there now) was created in a post-unicode world. You don't need to fuss or worry about setting the locale and the encoding... but if you have software that already does that, there's a chance it may break as the locale libraries are.... buggy. – Mahmoud Al-Qudsi Mar 17 '12 at 22:47
  • @MahmoudAl-Qudsi Localisation is something I think English-speaking developers (like me) find quite difficult; no longer can we just assume that the whole world speaks English :) It's not an easy aspect of any development even when you get the technology working; you still need to employee people to translate your product into other languages. That's something I am about to face myself, with some dread... – trojanfoe Mar 17 '12 at 23:00
  • When I say "locale management" I was referring to the C/C++/System locale settings, only. – Mahmoud Al-Qudsi Mar 17 '12 at 23:12