After 2 hours of searching and trying various methods, I'm pulling my hair out trying to print special ascii characters to the console! (C++)
typedef unsigned char UCHAR;
int main()
{
UCHAR c = '¥';
cout << c;
return 0;
}
Why does this code print Ñ (209) instead of ¥ (165)???
I've tried:
SetConsoleCP(CP_UTF8);
SetConsoleOutputCP(CP_UTF8);
but neither seems to do anything, no matter which values I pass to it.
Someone else suggested that the console's font needed to be changed through the registry. But that's ridiculous. I don't want my end users to have to start changing registry values simply to run my program...
the really odd thing is that if I print all the ascii characters to a file (using ofstream), they show up correctly both in notepad, and the visual studio editor (2012 professional).
ofstream file("ASCII.txt");;
if (file.is_open())
{
UCHAR c = 0;
for (int i = 0; i < 256; i++)
{
c++;
file << c << "\t|\t" << (int)c << endl;
}
}
file.close();
Any help is much appreciated. Thanks!
Welcome to the pain of encoding :(
#include <iostream>
#include <windows>
int main() {
SetConsoleCP(437);
SetConsoleOutputCP(437);
std::cout << (char)157 << "\n";
}
Generates:
The problem is that your source file is not in CP437 and therefore the character has a different value than the one you are trying to print (as you noted, in your source value is is 165 which is a different character in CP437).
来源:https://stackoverflow.com/questions/31083573/c-printing-special-ascii-characters-to-the-windows-console