C ++将特殊的ASCII字符打印到Windows控制台 [英] C++ Printing special ascii characters to the Windows console
问题描述
经过2个小时的搜索并尝试了各种方法之后,我将头发拉出来,尝试在控制台上打印特殊的ASCII字符! (C ++)
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;
}
为什么此代码显示Ñ(209)而不是¥(165)???
Why does this code print Ñ (209) instead of ¥ (165)???
我尝试过:
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...
真正奇怪的是,如果我将所有ascii字符打印到一个文件中(使用ofstream),它们在记事本和Visual Studio编辑器(2012专业版)中都能正确显示.
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";
}
生成:
问题是您的源文件在CP437中不是 ,因此该字符的值与您尝试打印的字符不同(如您所指出的,源值是165,即是CP437中的另一个字符).
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://en.wikipedia.org/wiki/Code_page_437
这篇关于C ++将特殊的ASCII字符打印到Windows控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!