在C ++中将Unicode写入文件 [英] Writing Unicode to a file in C++

查看:228
本文介绍了在C ++中将Unicode写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,使用C ++编写unicode到文件。我想写一个文件与我自己的扩展一些笑脸,你可以通过键入ALT + NUMPAD(2)获得。我可以通过制作一个字符并赋值'\2'到它显示一个笑脸,但它不会写入一个文件,它显示在CMD上。

I have a problem with writing unicode to a file in C++. I want to write to a file with my own extension a few smiley faces that you can get by typing ALT+NUMPAD(2). I can display it on CMD by making a char and assigning the value of '\2' to it and it will display a smiley face, but it won't write it to a file.

这里是我的程序的代码片段:

Here is a snippet of code for my program:

ofstream myfile;
myfile.open("C:\Users\My Username\test.exampleCodeFile");
myfile << "\2";
myfile.close();

它会写入文件,但不会显示我想要的。我会告诉你它显示什么,但StackOverflow不会让我显示的字符。提前感谢。

It will write to the file, but it wont display what I want. I would show you what it displays but StackOverflow won't let me display the character. Thanks in advance.

推荐答案

ALT + NUMPAD2与ASCII字符2不同,这是您的代码写入文件。 ALT代码是DOS如何处理非ASCII字符。 CMD.COM为ALT + NUMPAD2显示的字形实际上是Unicode码点U + 263BBLACK SMILING FACE。作为Unicode字符,最好是使用UTF-8或UTF-16编码文件,例如:

ALT+NUMPAD2 is not the same thing as ASCII character 2, which is what your code is writing to file. ALT codes are how DOS handles non-ASCII characters. The glyph that CMD.COM displays for ALT+NUMPAD2 is actually Unicode codepoint U+263B "BLACK SMILING FACE". Being a Unicode character, you are best off encoding the file using UTF-8 or UTF-16, eg:

ofstream myfile;
myfile.open("C:\\Users\My Username\\test.txt");
myfile << "\xEF\xBB\xBF"; // UTF-8 BOM
myfile << "\xE2\x98\xBB"; // U+263B
myfile.close();

ofstream myfile;
myfile.open("C:\\Users\\My Username\\test.txt");
myfile << "\xFF\xFE"; // UTF-16 BOM
myfile << "\x3B\x26"; // U+263B
myfile.close();

两种方法都在记事本中显示一个笑脸(如果您使用支持表情的字体)首先读取BOM,然后根据这一点解码Unicode码点。

Both approaches show a smiley face in Notepad (provided you use a Font that supports smileys), as it reads the BOM first and then decodes the Unicode codepoint accordingly based on that.

这篇关于在C ++中将Unicode写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆