System chcp 65001 что делает
Перейти к содержимому

System chcp 65001 что делает

  • автор:

2.4 Работа

В общем случае, создание программы начинается с создания проекта программы. В Code::Blocks для этого надо выбрать в меню File->New->Project. В появившемся окне выбрать Console application . Далее, в появившемся диалоговом окне нажать кнопку Next . В следующем диалоге следует указать название проекта, где он будет расположен, имя файла проекта и после ввода нажать кнопку Next . В следующем диалоге надо выбрать компилятор по умолчанию, стоит GCC, также надо отметить: какие режимы будет использовать ваш проект Debug — режим сборки приложения для отладки Release — режим сборки готового приложения. После выбора всего необходимого, следует нажать кнопку Next . В последнем диалоговом окне надо выбрать язык разработки приложения Си или Си++. И нажать кнопку

Подробнее создание проекта описано здесь [9].

2.4.2 Работа с проектом

При открытии нового проекта, надо в правой панели Management выбрать проект, и сделать двойной щелчок указателем мыши по объекту с именем Source . Список файлов проекта. Надо сделать ещё один щелчок по файлу, которой надо редактировать.

Подробнее создание проекта описано здесь [9].

2.5 Удаление

Для удаления среды необходимо просто удалить каталог с её файлами, куда была осуществлена установка. Для удаления MinGW и Gdb необходимо зайти в Панель управления , запустить Установка и удаление программ . Найти в списке установленных программ MinGW и Gdb, и выбрать удалить. Больше процесс удаления IDE никаких действий не требует.

3 Проблема ввода/вывода в консоли Windows XP ®

К сожалению при работе программы в консоли Windows возникают проблемы правильного отображения символов кириллицы. Есть несколько способов решить данную проблему. Эти способы будут рассмотрены далее. По идее какой-нибудь из них должен заработать.

Для начала необходимо убедиться, что исходный текст программы, который вы набираете, является текстом в кодировке UTF-8. Как это можно сделать для программы Code::Blocks описано в 2.3. Для других редакторов смотрите руководства по соответствующим IDE.

Подробнее можно почитать здесь[15].

Способ заключается в использовании функции WriteConsoleW () . Эта функция использует непосредственно вывод в консоль необходимого текста.

Чтобы работать с этой функцией, надо подключить заголовочный файл windows.h .

А использовать её можно, например так:

#include <iostream> #include <windows.h>

using namespace std ;

wchar_t * wstr = L «Привет мир!\n»; // наша строка для вывода DWORD written ;

WriteConsoleW ( GetStdHandle ( STD_OUTPUT_HANDLE ), wstr , wcslen ( wstr ) + 1 , & written , 0 );

где wchar_t — тип данных для работы с широкими символами, L — указывает, что передаваемая строка состоит из широких символов.

Можно воспользоваться функцией CharToOemW () для конвертации строк во время компиляции.

Чтобы работать с этой функцией надо подключить заголовочный файл windows.h .

Использовать её можно так:

#include <iostream> #include <windows.h>

using namespace std;

char buf [ 255 ]; // буфер — куда будет помещена

// конвертированная из UTF-8 в 866 строка. CharToOemW ( L «Привет мир!\n», buf ); // конвертация строки

cout << buf << endl ; // вывод строки в кодировке 866

Или, более удобный способ с использованием функции:

#include <iostream> #include <windows.h>

using namespace std;

char * UtfTo866 (const wchar_t * str )

char * buf = new char[ wcslen ( str ) + 1];

CharToOemW ( str , buf ); return buf ;

char * p = UtfTo866 ( L «Привет мир!\n»); cout << p << endl ;

Ещё один вариант с использованием типа string вместо указателя:

#include <iostream> #include <string> #include <windows.h>

using namespace std;

string UtfTo866 (const wchar_t * str )

char * buf = new char[ wcslen ( str ) + 1]; string tstr;

CharToOemW ( str , buf );

tstr = buf ; delete buf ;

cout << UtfTo866 ( L «Привет мир!\n») << endl ;

Или, более правильный способ для языка Си++ с использованием класса: файл utfto866.h

#ifndef UTFTO866_H #define UTFTO866_H

#include <iostream> #include <windows.h>

std :: string str ; public:

UtfTo866 (const UtfTo866 & other ); virtual

UtfTo866 & operator=(const UtfTo866 & other );

std :: string utf8to866 (const wchar_t * m_str ); void setstring ( std :: string m_str );

void setutf8 (const wchar_t * m_str ); std :: string get866 () const;

#endif // UTFTO866_H файл utfto866.cpp

UtfTo866 :: UtfTo866 (const UtfTo866 & other ): str ( other . str )

UtfTo866 & UtfTo866 ::operator=(const UtfTo866 & rhs )

if(this == & rhs ) return *this; str = rhs . str ;

std :: string UtfTo866 :: utf8to866 (const wchar_t * m_str )

char * std_char = new char[ std :: wcslen ( m_str ) + 1 ]; CharToOemW(m_str, std_char );

void UtfTo866 :: setstring ( std :: string m_str )

char * std_char = new char[ m_str . length () + 1 ]; wchar_t * s = new wchar_t[ m_str . length () + 1 ]; strcpy ( std_char , m_str . c_str ());

s = (wchar_t*) std_char ;

CharToOemW ( s , std_char ); str = std_char ;

delete [] std_char ; delete [] s ;

void UtfTo866 :: setutf8 (const wchar_t * m_str )

char * std_char = new char[ std :: wcslen ( m_str ) + 1 ];

CharToOemW ( m_str , std_char );

std :: string UtfTo866 :: get866 () const

using namespace std ;

// поэтапное использование класса

// сначало помещение строки, потом вывод

m . utf8to866 ( L «1 — Привет мир!\n»); // помещение строки в класс cout << m . get866 () << endl ; // вывод строки из класса

// одновременное помещение строки и вывод

cout << m . utf8to866 ( L «2 — Привет мир!\n») << endl ;

Следует задать в консоли кодировку, в которой будет выполняться ваша программа.

Задаётся она следующей командой:

Но прежде, в консоли (командной строке) необходимо поменять шрифт с «Точечные шрифты» на «Lucinda Console» . Делается это через свойства командной строки, которое можно открыть, щёлкнув правой кнопкой мыши по заголовку окна «Командная строка».

Для непосредственного выполнения команды chcp в вашей программе можно воспользоваться функцией system () , например так:

#include <stdio.h> #include <stdlib.h>

system («chcp 65001»); printf («Привет мир!\n»); return 0 ;

Пример был приведён для языка Си но для Си++ он также работоспособен.

Последний способ заключается в использовании функций в Си или методов Си++ специально предназначенных для работы с широкими символами. Таких как wcout или wprintf () .

Прежде чем использовать данные функции, необходимо установить локаль (англ. locale) приложения, это можно сделать функцией setlocale () .

Чтобы работать с этой функцией, надо подключить заголовочный файл locale.h .

Using UTF-8 Encoding (CHCP 65001) in Command Prompt / Windows Powershell (Windows 10)

I’ve been forcing the usage of chcp 65001 in Command Prompt and Windows Powershell for some time now, but judging by Q&A posts on SO and several other communities it seems like a dangerous and inefficient solution. Does Microsoft provide an improved / complete alternative to chcp 65001 that can be saved permanently without manual alteration of the Registry? And if there isn’t, is there a publicly announced timeline or agenda to support UTF-8 in the Windows CLI in the future?

Personally I’ve been using chcp 949 for Korean Character Support, but the weird display of the backslash \ and incorrect/incomprehensible displays in several applications (like Neovim), as well as characters that aren’t Korean not being supported via 949 seems to become more of a problem lately.

Paul Kim's user avatar

3 Answers 3

This answer shows how to switch the character encoding in the Windows console to
(BOM-less) UTF-8 (code page 65001 ), so that shells such as cmd.exe and PowerShell properly encode and decode characters (text) when communicating with external (console) programs with full Unicode support, and in cmd.exe also for file I/O. [1]

If, by contrast, your concern is about the separate aspect of the limitations of Unicode character rendering in console windows, see the middle and bottom sections of this answer, where alternative console (terminal) applications are discussed too.

Does Microsoft provide an improved / complete alternative to chcp 65001 that can be saved permanently without manual alteration of the Registry?

As of (at least) Windows 10, version 1903, you have the option to set the system locale (language for non-Unicode programs) to UTF-8, but the feature is still in beta as of this writing.

  • Run intl.cpl (which opens the regional settings in Control Panel)
  • Follow the instructions in the screen shot below.

Control Panel > Region > Administrative

This sets both the system’s active OEM and the ANSI code page to 65001 , the UTF-8 code page, which therefore (a) makes all future console windows, which use the OEM code page, default to UTF-8 (as if chcp 65001 had been executed in a cmd.exe window) and (b) also makes legacy, non-Unicode GUI-subsystem applications, which (among others) use the ANSI code page, use UTF-8.

Caveats:

If you’re using Windows PowerShell, this will also make Get-Content and Set-Content and other contexts where Windows PowerShell default so the system’s active ANSI code page, notably reading source code from BOM-less files, default to UTF-8 (which PowerShell Core (v6+) always does). This means that, in the absence of an -Encoding argument, BOM-less files that are ANSI-encoded (which is historically common) will then be misread, and files created with Set-Content will be UTF-8 rather than ANSI-encoded.

[Fixed in PowerShell 7.1] Up to at least PowerShell 7.0, a bug in the underlying .NET version (.NET Core 3.1) causes follow-on bugs in PowerShell: a UTF-8 BOM is unexpectedly prepended to data sent to external processes via stdin (irrespective of what you set $OutputEncoding to), which notably breaks Start-Job — see this GitHub issue.

Not all fonts speak Unicode, so pick a TT (TrueType) font, but even they usually support only a subset of all characters, so you may have to experiment with specific fonts to see if all characters you care about are represented — see this answer for details, which also discusses alternative console (terminal) applications that have better Unicode rendering support.

As eryksun points out, legacy console applications that do not "speak" UTF-8 will be limited to ASCII-only input and will produce incorrect output when trying to output characters outside the (7-bit) ASCII range. (In the obsolescent Windows 7 and below, programs may even crash).
If running legacy console applications is important to you, see eryksun’s recommendations in the comments.

However, for Windows PowerShell, that is not enough:

  • You must additionally set the $OutputEncoding preference variable to UTF-8 as well: $OutputEncoding = [System.Text.UTF8Encoding]::new() [2] ; it’s simplest to add that command to your $PROFILE (current user only) or $PROFILE.AllUsersCurrentHost (all users) file.
  • Fortunately, this is no longer necessary in PowerShell Core, which internally consistently defaults to BOM-less UTF-8.

If setting the system locale to UTF-8 is not an option in your environment, use startup commands instead:

Note: The caveat re legacy console applications mentioned above equally applies here. If running legacy console applications is important to you, see eryksun’s recommendations in the comments.

For PowerShell (both editions), add the following line to your $PROFILE (current user only) or $PROFILE.AllUsersCurrentHost (all users) file, which is the equivalent of chcp 65001 , supplemented with setting preference variable $OutputEncoding to instruct PowerShell to send data to external programs via the pipeline in UTF-8:

  • Note that running chcp 65001 from inside a PowerShell session is not effective, because .NET caches the console’s output encoding on startup and is unaware of later changes made with chcp ; additionally, as stated, Windows PowerShell requires $OutputEncoding to be set — see this answer for details.
  • For example, here’s a quick-and-dirty approach to add this line to $PROFILE programmatically:

For cmd.exe , define an auto-run command via the registry, in value AutoRun of key HKEY_CURRENT_USER\Software\Microsoft\Command Processor (current user only) or HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor (all users):

  • For instance, you can use PowerShell to create this value for you:

Optional reading: Why the Windows PowerShell ISE is a poor choice:

While the ISE does have better Unicode rendering support than the console, it is generally a poor choice:

First and foremost, the ISE is obsolescent: it doesn’t support PowerShell (Core) 7+, where all future development will go, and it isn’t cross-platform, unlike the new premier IDE for both PowerShell editions, Visual Studio Code, which already speaks UTF-8 by default for PowerShell Core and can be configured to do so for Windows PowerShell.

The ISE is generally an environment for developing scripts, not for running them in production (if you’re writing scripts (also) for others, you should assume that they’ll be run in the console); notably, with respect to running code, the ISE’s behavior is not the same as that of a regular console:

Poor support for running external programs, not only due to lack of supporting interactive ones (see next point), but also with respect to:

character encoding: the ISE mistakenly assumes that external programs use the ANSI code page by default, when in reality it is the OEM code page. E.g., by default this simple command, which tries to simply pass a string echoed from cmd.exe through, malfunctions (see below for a fix):
cmd /c echo hü | Write-Output

Inappropriate rendering of stderr output as PowerShell errors: see this answer.

The ISE dot-sources script-file invocations instead of running them in a child scope (the latter is what happens in a regular console window); that is, repeated invocations run in the very same scope. This can lead to subtle bugs, where definitions left behind by a previous run can affect subsequent ones.

As eryksun points out, the ISE doesn’t support running interactive external console programs, namely those that require user input:

The problem is that it hides the console and redirects the process output (but not input) to a pipe. Most console applications switch to full buffering when a file is a pipe. Also, interactive applications require reading from stdin, which isn’t possible from a hidden console window. (It can be unhidden via ShowWindow , but a separate window for input is clunky.)

If you’re willing to live with that limitation, switching the active code page to 65001 (UTF-8) for proper communication with external programs requires an awkward workaround:

You must first force creation of the hidden console window by running any external program from the built-in console, e.g., chcp — you’ll see a console window flash briefly.

Only then can you set [console]::OutputEncoding (and $OutputEncoding ) to UTF-8, as shown above (if the hidden console hasn’t been created yet, you’ll get a handle is invalid error ).

H Кодировка символов и Console в черновиках Tutorial

Кодировка символов в памяти и отображения символов на устройстве, это не одно и тоже, кодировка в памяти может быть разной даже в контексте одной программы, а отображение должно любой контекст интерпретировать правильно, и опять же определить контекст полагается программисту, а не устройству которое будет отображать символ.

Современные программисты также как и учебники программирования, стали забывать что программист должен контролировать все устройства ввода вывода, а не операционная система. в связи с этим начинающие программисты не понимают почему программа которая написана корректно с точки зрения алгоритмов работает не правильно, то есть не отображает символы так как задумал программист.

Немного практики

В современном мире, почти все кодировки и отображение контролирует операционная система, чаще всего в Windows отображаются кракозябры, а в Linux все хорошо, и новичкам советуют ставить Linux и не «париться», это в корне не верный подход, На самом деле все дело в настройках операционной системе на которой вы работаете. В Linux кодировка и отображение кодировки настроено на стандарт unicode utf-8 или unicode utf-32le (смотря какой конкретный дистрибутив) и оба стандарта совместимы, а в Windows исторически сложилось Legacy разработка, настройка кодировки отображения идет в console cp866(Если вы используете русский диструбутив windows) а winapi использует code pages 1251(На русском дистрибутиве) в связи с этим у нас несколько путей решения:

    Сохранять исходные коды в cp866 чтобы компилятор или интерпретатор «вшивал» код символов для conosle windows по умолчанию.

Change default code page of Windows console to UTF-8

Currently I’m running Windows 7 x64 and usually I want all console tools to work with UTF-8 rather than with default code page 850.

Running chcp 65001 in the command prompt prior to use of any tools helps but is there any way to set is as default code page?

Update:

Changing HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage\OEMCP value to 65001 appear to make the system unable to boot in my case.

Proposed change of HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\Autorun to @chcp 65001>nul served just well for my purpose. (thanks to Ole_Brun)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *