C++ Visual Studio character encoding issues
Using _setmode()
works¹ and is arguably better than changing the codepage or setting a locale, since it'll actually make your program output in Unicode and thus will be consistent - no matter which codepage or locale are currently set.
Example:
#include <iostream>
#include <io.h>
#include <fcntl.h>
int wmain()
{
_setmode( _fileno(stdout), _O_U16TEXT );
std::wcout << L"à éêù" << std::endl;
return 0;
}
Inside Visual Studio, make sure you set up your project for Unicode (Right-click *Project* -> Click *General* -> *Character Set* = *Use Unicode Character Set*).
MinGW users:
- Define both
UNICODE
and_UNICODE
- Add
-finput-charset=iso-8859-1
to the compiler options to get around this error: "converting to execution character set: Invalid argument" - Add
-municode
to the linker options to get around "undefined reference to `WinMain@16" (read more).
**Edit:** The equivalent call to set unicode *input* is: `_setmode( _fileno(stdin), _O_U16TEXT );`
Edit 2: An important piece of information, specially considering the question uses std::cout
. This is not supported. The MSDN Docs states (emphasis mine):
Unicode mode is for wide print functions (for example, wprintf) and is not supported for narrow print functions. Use of a narrow print function on a Unicode mode stream triggers an assert.
So, don't use std::cout
when the console output mode is _O_U16TEXT
; similarly, don't use std::cin
when the console input is _O_U16TEXT
. You must use the wide version of these facilities (std::wcout
, std::wcin
).
And do note that mixing cout
and wcout
in the same output is not allowed (but I find it works if you call flush()
and then _setmode()
before switching between the narrow and wide operations).
Before I go any further, I should mention that what you are doing is not c/c++ compliant. The specification states in 2.2 what character sets are valid in source code. It ain't much in there, and all the characters used are in ascii. So... Everything below is about a specific implementation (as it happens, VC2008 on a US locale machine).
To start with, you have 4 chars on your cout
line, and 4 glyphs on the output. So the issue is not one of UTF8 encoding, as it would combine multiple source chars to less glyphs.
From you source string to the display on the console, all those things play a part:
- What encoding your source file is in (i.e. how your C++ file will be seen by the compiler)
- What your compiler does with a string literal, and what source encoding it understands
- how your
<<
interprets the encoded string you're passing in - what encoding the console expects
- how the console translates that output to a font glyph.
Now...
1 and 2 are fairly easy ones. It looks like the compiler guesses what format the source file is in, and decodes it to its internal representation. It generates the string literal corresponding data chunk in the current codepage no matter what the source encoding was. I have failed to find explicit details/control on this.
3 is even easier. Except for control codes, <<
just passes the data down for char *.
4 is controlled by SetConsoleOutputCP
. It should default to your default system codepage. You can also figure out which one you have with GetConsoleOutputCP
(the input is controlled differently, through SetConsoleCP
)
5 is a funny one. I banged my head to figure out why I could not get the é to show up properly, using CP1252 (western european, windows). It turns out that my system font does not have the glyph for that character, and helpfully uses the glyph of my standard codepage (capital Theta, the same I would get if I did not call SetConsoleOutputCP). To fix it, I had to change the font I use on consoles to Lucida Console (a true type font).
Some interesting things I learned looking at this:
- the encoding of the source does not matter, as long as the compiler can figure it out (notably, changing it to UTF8 did not change the generated code. My "é" string was still encoded with CP1252 as
233 0
) - VC is picking a codepage for the string literals that I do not seem to control.
- controlling what the console shows is more painful than what I was expecting
So... what does this mean to you ? Here are bits of advice:
- don't use non-ascii in string literals. Use resources, where you control the encoding.
- make sure you know what encoding is expected by your console, and that your font has the glyphs to represent the chars you send.
- if you want to figure out what encoding is being used in your case, I'd advise printing the actual value of the character as an integer.
char * a = "é"; std::cout << (unsigned int) (unsigned char) a[0]
does show 233 for me, which happens to be the encoding in CP1252.
BTW, if what you got was "ÃÃè" rather than what you pasted, then it looks like your 4 bytes are interpreted somewhere as CP850.
Because I was requested to, Iâll do some necromancy. The other answers were from 2009, but this article still came up on a search I did in 2018. The situation today is very different. Also, the accepted answer was incomplete even back in 2009.
The Source Character Set
Every compiler (including Microsoftâs Visual Studio 2008 and later, gcc, clang and icc) will read UTF-8 source files that start with BOM without a problem, and clang will not read anything but UTF-8, so UTF-8 with a BOM is the lowest common denominator for C and C++ source files.
The language standard doesnât say what source character sets the compiler needs to support. Some real-world source files are even saved in a character set incompatible with ASCII. Microsoft Visual C++ in 2008 supported UTF-8 source files with a byte order mark, as well as both forms of UTF-16. Without a byte order mark, it would assume the file was encoded in the current 8-bit code page, which was always a superset of ASCII.
The Execution Character Sets
In 2012, the compiler added a /utf-8
switch to CL.EXE
. Today, it also supports the /source-charset
and /execution-charset
switches, as well as /validate-charset
to detect if your file is not actually UTF-8. This page on MSDN has a link to the documentation on Unicode support for every version of Visual C++.
Current versions of the C++ standard say the compiler must have both an execution character set, which determines the numeric value of character constants like 'a'
, and a execution wide-character set that determines the value of wide-character constants like L'é'
.
To language-lawyer for a bit, there are very few requirements in the standard for how these must be encoded, and yet Visual C and C++ manage to break them. It must contain about 100 characters that cannot have negative values, and the encodings of the digits '0'
through '9'
must be consecutive. Neither capital nor lowercase letters have to be, because they werenât on some old mainframes. (That is, '0'+9
must be the same as '9'
, but there is still a compiler in real-world use today whose default behavior is that 'a'+9
is not 'j'
but '«'
, and this is legal.) The wide-character execution set must include the basic execution set and have enough bits to hold all the characters of any supported locale. Every mainstream compiler supports at least one Unicode locale and understands valid Unicode characters specified with \Uxxxxxxxx
, but a compiler that didnât could claim to be complying with the standard.
The way Visual C and C++ violate the language standard is by making their wchar_t
UTF-16, which can only represent some characters as surrogate pairs, when the standard says wchar_t
must be a fixed-width encoding. This is because Microsoft defined wchar_t
as 16 bits wide back in the 1990s, before the Unicode committee figured out that 16 bits were not going to be enough for the entire world, and Microsoft was not going to break the Windows API. It does support the standard char32_t
type as well.
UTF-8 String Literals
The third issue this question raises is how to get the compiler to encode a string literal as UTF-8 in memory. Youâve been able to write something like this since C++11:
constexpr unsigned char hola_utf8[] = u8"¡Hola, mundo!";
This will encode the string as its null-terminated UTF-8 byte representation regardless of whether the source character set is UTF-8, UTF-16, Latin-1, CP1252, or even IBM EBCDIC 1047 (which is a silly theoretical example but still, for backward-compatibility, the default on IBMâs Z-series mainframe compiler). That is, itâs equivalent to initializing the array with { 0xC2, 0xA1, 'H', /* ... , */ '!', 0 }
.
If it would be too inconvenient to type a character in, or if you want to distinguish between superficially-identical characters such as space and non-breaking space or precomposed and combining characters, you also have universal character escapes:
constexpr unsigned char hola_utf8[] = u8"\u00a1Hola, mundo!";
You can use these regardless of the source character set and regardless of whether youâre storing the literal as UTF-8, UTF-16 or UCS-4. They were originally added in C99, but Microsoft supported them in Visual Studio 2015.
Edit: As reported by Matthew, u8"
strings are buggy in some versions of MSVC, including 19.14. It turns out, so are literal non-ASCII characters, even if you specify /utf-8
or /source-charset:utf-8 /execution-charset:utf-8
. The sample code above works properly in 19.22.27905.
There is another way to do this that worked in Visual C or C++ 2008, however: octal and hexadecimal escape codes. You would have encoded UTF-8 literals in that version of the compiler with:
const unsigned char hola_utf8[] = "\xC2\xA1Hello, world!";
Try this:
#include <iostream>
#include <locale>
int main()
{
std::locale::global(std::locale(""));
std::cout << "à éêù" << std::endl;
return 0;
}