How to print UTF-8 characters in c ++ console?

1

The console incorrectly displays accented characters. How to print them correctly (UTF-8)?

    
asked by anonymous 20.05.2018 / 02:16

2 answers

0

1st declare library: #include <locale.h>
2nd place at the beginning of the main function:
setlocale(LC_ALL,""); // Este comando pega a codificação da maquina que está rodando.

#include <iostream>
#include <locale.h>    
using namespance std;
int main(){

setlocale(LC_ALL,"");

cout <<"Acento é legal =D "<< endl;

}       
    
20.05.2018 / 02:25
2

You're probably referring to the Windows console, or cmd.exe .

By default, cmd.exe does not work with output encoding UTF-8 , also known as a Code Page 65001 .

To change it, simply enter the command in the console:

chcp 65001

Alternatively you can start the console already with the output encoding set to UTF-8 , let's see:

1) Press Windows + R ;

2) Run the following command:

cmd.exe /K chcp 65001 

Following is a program with C++ able to test whether the console has been properly configured:

#include <iostream>
#include <locale>


int main(){

    setlocale( LC_ALL, "" );

    std::wstring ch = L"你好世界";
    std::wstring gk = L"γειά σου κόσμος";
    std::wstring jp = L"こんにちは世界";
    std::wstring ko = L"여보세요 세계";
    std::wstring pt = L"Olá mundo!";
    std::wstring ru = L"Здравствулте мир!";

    std::wcout << L"Chinês    : " << ch << std::endl;
    std::wcout << L"Grego     : " << gk << std::endl;
    std::wcout << L"Japonês   : " << jp << std::endl;
    std::wcout << L"Coreano   : " << ko << std::endl;
    std::wcout << L"Português : " << pt << std::endl;
    std::wcout << L"Russo     : " << ru << std::endl;

}

Output:

Chinês    : 你好世界
Grego     : γειά σου κόσμος
Japonês   : こんにちは世界
Coreano   : 여보세요 세계
Português : Olá mundo!
Russo     : Здравствулте мир!

References:

chcp: link

    
20.05.2018 / 03:12