如何使std :: wofstream编写UTF-8? [英] How to make std::wofstream write UTF-8?
问题描述
我将std::wclog
重定向到文件以登录程序:
I am redirecting std::wclog
to a file for logging in my program:
std::wclog.rdbuf((new std::wofstream("C:\\path\\to\\file.log", std::ios::app))->rdbuf());
通过写入std::wclog
进行记录:
std::wclog << "Schöne Grüße!" << std::endl;
令人惊讶的是,我发现该文件是用ANSI编写的. (这对于ofstream
和clog
是完全可以接受的,但是我曾期望wofstream
和wclog
产生某种unicode输出.)我也希望能够登录CYK语言(例如,用户输入),因此是否有办法让wofstream
生成UTF-8?开放模式标志似乎不提供此功能.
Surprisingly I found that the file is being written in ANSI. (This would be totally acceptable for ofstream
and clog
, but I had expected wofstream
and wclog
to produce some kind of unicode output.) I want to be able to log in CYK langugages as well (e.g. user input), so is there a way to get wofstream
to produce UTF-8? The openmode flags seem not to provide for this.
(如果没有独立于平台的方式,则我使用的是Win7 + 64位.)
(If there isn’t a platform-independent way, I am on Win7+ 64-bit.)
上面的问题有一个错误.线
There is an error in the question above. The line
std::wclog << "Schöne Grüße!" << std::endl;
应该正确
std::wclog << L"Schöne Grüße!" << std::endl;
这只是为了演示我想做的事,在现实生活中,被写入wofstream
的wstring
来自提供翻译的类,例如
This is just to demonstrate what I want to do, in real life the wstring
being written to the wofstream
comes out of a class which provides for translation, like
std::wclog << _(L"Best regards") << std::endl;
其中
#define _(X) i18n::translate(X)
class i18n {
public:
static std::wstring translate(const std::wstring&);
}
所以我要做的是使用wofstring
将wstring
写入std::wclog
并将其放入文件中,并且该文件应采用UTF-8编码(无BOM).
So what I want to do is to write a wstring
to std::wclog
using an wofstring
to put it into a file, and that file should be UTF-8 encoded (without BOM).
推荐答案
所有您需要使用的是UTF8文字,即:
All you need is to use a UTF8 literal, ie:
std::wclog << u8"Schöne Grüße!" << std::endl;
结果将是
SchöneGrüße!
Schöne Grüße!
如果您混合使用ASCII和UTF8文字,例如:
If you mix ASCII and UTF8 literals, eg:
std::wclog << "Schöne Grüße!" << std::endl << u8"Schöne Grüße!" <<
std :: endl;
std::endl;
将替换非ASCII字符.
the non-ASCII characters will be replaced.
Sch?ne Gr ?? e!
舍恩·格吕斯(SchöneGrüße)!
Sch?ne Gr??e!
Schöne Grüße!
Unicode文字已添加到C ++ 11中.它们首先在Visual Studio 2015中实现.
Unicode literals were added to C++ 11. They were first implemented in Visual Studio 2015. The String and Character Literals page describes the literals that are supported in Visual C++ at the moment.
这篇关于如何使std :: wofstream编写UTF-8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!