I'm trying to write unicode strings to the screen in C++ on Windows. I changed my console font to Lucida Console
and I set the output to CP_UTF8
aka 65001.
I run the following code:
#include <stdio.h> //notice this header file..
#include <windows.h>
#include <iostream>
int main()
{
SetConsoleOutputCP(CP_UTF8);
const char text[] = "Россия";
printf("%s\n", text);
}
It prints out just fine!
However, if I do:
#include <cstdio> //the C++ version of the header..
#include <windows.h>
#include <iostream>
int main()
{
SetConsoleOutputCP(CP_UTF8);
const char text[] = "Россия";
printf("%s\n", text);
}
it prints: ������������
I have NO clue why..
Another thing is when I do:
#include <windows.h>
#include <iostream>
int main()
{
std::uint32_t oldcodepage = GetConsoleOutputCP();
SetConsoleOutputCP(CP_UTF8);
std::string text = u8"Россия";
std::cout<<text<<"\n";
SetConsoleOutputCP(oldcodepage);
}
I get the same output as above (non-working output).
Using printf
on the std::string
, it works fine though:
#include <stdio.h>
#include <windows.h>
#include <iostream>
int main()
{
std::uint32_t oldcodepage = GetConsoleOutputCP();
SetConsoleOutputCP(CP_UTF8);
std::string text = u8"Россия";
printf("%s\n", text.c_str());
SetConsoleOutputCP(oldcodepage);
}
but only if I use stdio.h
and NOT cstdio
.
Any ideas how I can use std::cout
? How can I use cstdio
as well?
Why does this happen? Isn't cstdio
just a c++ version of stdio.h
?
EDIT: I've just tried:
#include <iostream>
#include <io.h>
#include <fcntl.h>
int main()
{
_setmode(_fileno(stdout), _O_U8TEXT);
std::wcout << L"Россия" << std::endl;
}
and yes it works but only if I use std::wcout
and wide strings
. I would really like to avoid wide-strings
and the only solution I see so far is the C-printf
:l
So the question still stands..