How can I open .cpp file in visual studio and make it display string literals with Cyrillic characters correctly?

Viewed 425

I'm trying to open source file with C++ code from another person. While writing the code he used older version of visual studio then I have right now. Cyrillic letters are distorted.

Stupidly confusing part of it is encoding problem. When I open .cpp file with any program, that can read text except for notepad++ English characters are displayed perfectly, but Cyrillic are distorted. Notepad++ shows that it opens that file in ANSI encoding. If I copy that correctly displayed text from notepad++ to other program (visual studio, standard windows notepad, google translator in browser, some online encoding converter) it becomes distorted again as if it was copying bytes instead of characters (this one blows my mind most of all). Since .cpp file is basically just text file, I don't understand why can't I read it. And if it was damaged file - notepad++ wouldn't read it. Or at least it would show some error message, wouldn't it?

Here is how visual studio displays it:

cout << "����� ����� � ������� 100-999";
cout << "\n�������� 2 (��i� ����� �� � �� ������� �����) = " << d;
cout << "\n�������� 3 (��i� ����� �� �� �� ��������� ����) = " << f << "\n";

Here is correct code:

cout << "серед чисел в діапазоні 100-999";
cout << "\nзавдання 2 (усіх чисел де є дві однакові цифри) = " << d;
cout << "\nзавдання 3 (усіх чисел де не має однакових цифр) = " << f << "\n";

P.S. I know that questions about encoding were asked already billion times, but I didn't find proper answer, so please don't hit me too hard if it was answered before. Thanks in advance.

2 Answers

I can suggest a working solution for your problem which works fine in my Visual Studio 2017 and ConEmu with UTF-8 encoding output.

First of all use u8 literal strings which gives you UTF-8 output:

#include <iostream>

int main()
{
    double d = 0.0;
    double f = 1.0;
    std::cout << u8"серед чисел в діапазоні 100-999";
    std::cout << u8"\nзавдання 2 (усіх чисел де є дві однакові цифри) = " << d;
    std::cout << u8"\nзавдання 3 (усіх чисел де не має однакових цифр) = " << f << "\n";
    return 0;
}

Then compile and run your program under ConEmu console emulator which supports UTF-8 output. Accordling to ConEmu Unicode support documentation you need to switch to UTF-8 with command chcp 65001:

chcp 65001
test.exe

It gives me the following result:

enter image description here

Save the file in Unicode encoding, preferably UTF8. Go to File menu and click Save As

enter image description here

When you click "Save with Encoding...", Visual Studio should give at least two UTF8 options:

"UTF8 with signature"
"UTF8 without signature"

Microsoft products prefer UTF8 with signature (BOM), whereas Notepad++ prefer UTF8 without signature.

Related