1

I need to write a C++ that reads country names in Portuguese (Latin language with special characters like é and á)

This is the code I am using:

int main(int, const char *[])
{
    setlocale(LC_ALL, "en_US.UTF-8");
    locale accents("en_US.UTF-8");
    wcout.imbue(accents);
    
    wstring belgium, italy;
    
    belgium = L"bélgica"; italy = L"itália";
    wcout << L"Result: " << setw(15) << belgium << endl;
    wcout << L"Result: " << setw(15) << italy << endl;
    wcout << L"Result: " << setw(15) << L"portugal" << endl << endl;
    
    wcout << L"Input 'bélgica itália': "; wcin >> belgium >> italy;
    wcout << L"Result: " << setw(15) << belgium << endl;
    wcout << L"Result: " << setw(15) << italy << endl;
    wcout << L"Result: " << setw(15) << L"portugal" << endl;
}

And this is the result I get:

Result:         bélgica
Result:          itália
Result:        portugal

Input 'bélgica itália': bélgica itália
Result:        bélgica
Result:         itália
Result:        portugal

So, you can see on the first part of the code, I attribute the values L"bélgica" to variable belgium and L"itália" to italy. When I display the variables' contents, everything is perfect: accents come out right and setw does its job properly understanding that "é" and "á" are a single character, so both countries' names come aligned with "portugal".

The second part of the code is what is bugging me: I now use wcin to get the values of variables belgium and italy, but the results are not as I expected.

Can you help me, please?

Nuno
  • 117
  • 4
  • Is this Windows? `_setmode(_fileno(stdout), _O_U16TEXT); _setmode(_fileno(stdin), _O_U16TEXT);` seems to work - from this answer [Cin and getline won't save non ascii characters correctly](https://stackoverflow.com/a/58924656) – 001 Oct 15 '21 at 18:12
  • No, this is on a Mac. – Nuno Oct 15 '21 at 19:18
  • Maybe try `wcin.imbue(accents);` – 001 Oct 15 '21 at 21:08
  • I did try that before. I get this result: belgium = "bb", italy = "itália" – Nuno Oct 15 '21 at 23:24

0 Answers0