1

C ++でユニコードを処理する適切な方法を見つけようとしています。g++ がリテラル ワイド文字列と、Unicode 文字を含む通常の C 文字列をどのように処理するかを理解したいと思います。いくつかの基本的なテストを設定しましたが、何が起こっているのかよくわかりません。

wstring ws1(L"«¬.txt"); // these first 2 characters correspond to 0xAB, 0xAC
string s1("«¬.txt");

ifstream in_file( s1.c_str() );
// wifstream in_file( s1.c_str() ); // this throws an exception when I 
                                    // call in_file >> s;
string s;
in_file >> s; // s now contains «¬

wstring ws = textToWide(s);

wcout << ws << endl; // these two lines work independently of each other,
                     // but combining them makes the second one print incorrectly
cout << s << endl;
printf( "%s", s.c_str() ); // same case here, these work independently of one another,
                           // but calling one after the other makes the second call
                           // print incorrectly
wprintf( L"%s", ws.c_str() );

wstring textToWide(string s)
{
    mbstate_t mbstate;
    char *cc = new char[s.length() + 1];
    strcpy(cc, s.c_str());
    cc[s.length()] = 0;
    size_t numbytes = mbsrtowcs(0, (const char **)&cc, 0, &mbstate);
    wchar_t *buff = new wchar_t[numbytes + 1];
    mbsrtowcs(buff, (const char **)&cc, numbytes + 1, &mbstate);
    wstring ws = buff;
    delete [] cc;
    delete [] buff;
    return ws;
}

wcout と wprintf を呼び出すと何らかの形でストリームが破損するようで、文字列が utf-8 としてエンコードされている限り、cout と printf を呼び出すことは常に安全です。

Unicode を処理する最善の方法は、処理前にすべての入力をワイドに変換し、outupt に送信する前にすべての出力を utf-8 に変換することでしょうか?

4

1 に答える 1