Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wcout function does not print a french character

Tags:

c++

g++

wchar-t

I am using the wcin in order to store a single character in a wchar_t. Then I try to print it with a wcout call and the french character 'é' : but I can't see it at my console.

My compiler is g++ 4.5.4 and my OS is Ubuntu 12.10 64 bits.

Here is my attempt (wideChars.cpp) :

#include <iostream>

int main(){
    using namespace std;

    wchar_t aChar;
    cout << "Enter your char : ";
    wcin >> aChar;
    wcout << L"You entered " << aChar << L" .\n";

    return 0;
}

When I lauch the programm :

$ ./wideChars 
Enter your char : é
You entered  .

So, what's wrong with this code ?

like image 682
loloof64 Avatar asked Oct 22 '22 14:10

loloof64


1 Answers

First, add some error checking. Test what does wcin.good() return after the input and what does wcout.good() return after the "You entered" print? I suspect one of those will return false.

What are your LANG and LC_* environment variables set to?

Then try to fix this by adding this at the top of your main(): wcin.imbue(std::locale("")); wcout.imbue(std::locale(""));

I do not have my Ubuntu at hand right now, so I am flying blind here and mostly guessing.

UPDATE

If the above suggestion does not help then try to construct locale like this and imbue() this locale instead.

std::locale loc (
    std::locale (),
    new std::codecvt_byname<wchar_t, char, std::mbstate_t>("")));

UPDATE 2

Here is what works for me. The key is to set the C locale as well. IMHO, this is a bug in GNU C++ standard library implementation. Unless I am mistaken, setting std::locale::global(""); should also set the C library locale.

#include <iostream>
#include <locale>
#include <clocale>

#define DUMP(x) do { std::wcerr << #x ": " << x << "\n"; } while (0)

int main(){
    using namespace std;

    std::locale loc ("");
    std::locale::global (loc);
    DUMP(std::setlocale(LC_ALL, NULL));
    DUMP(std::setlocale(LC_ALL, ""));    
    wcin.imbue (loc);

    DUMP (wcin.good());
    wchar_t aChar = 0;
    wcin >> aChar;
    DUMP (wcin.good());
    DUMP ((int)aChar);
    wcout << L"You entered " << aChar << L" .\n";

    return 0;
}

UPDATE 3

I am confused, now I cannot reproduce it again and setting std::locale::global(loc); seems to do the right thing wrt/ the C locale as well.

like image 114
wilx Avatar answered Oct 24 '22 05:10

wilx