我使用VS2008编写了以下程序:
#include <fstream>
int main()
{
std::wofstream fout("myfile");
fout << L"Հայաստան Россия Österreich Ελλάδα भारत" << std::endl;
}当我试图编译它时,IDE问我是否想用unicode保存我的源文件,我说“是的,请”。
然后我运行程序,我的文件出现在我的项目的文件夹中。我用记事本打开的,文件是空的。我记得记事本只支持ASCII数据。我用WordPad打开它,它仍然是空的。最后,我内心的小天才催促我看看文件的大小,毫不奇怪,它是0字节。所以我重建并重新运行了这个程序,没有效果。最后,我决定在StackOverflow上询问非常聪明的人我缺少的是什么,我在这里:)
编辑:
在上面的聪明人留下了一些评论之后,我决定听从他们的建议,改写程序如下:
#include <fstream>
#include <iostream>
int main()
{
std::wofstream fout("myfile");
if(!fout.is_open())
{
std::cout << "Before: Not open...\n";
}
fout << L"Հայաստան Россия Österreich Ελλάδα भारत" << std::endl;
if(!fout.good())
{
std::cout << "After: Not good...\n";
}
}建造了它。查过了。还有..。控制台上写得很清楚,让我吃惊的是:“之后:不好……”。因此,我编辑了我的帖子,提供了新的信息,并开始等待答案,这将解释这是为什么,我可以做什么。:)
发布于 2010-10-16 21:06:12
在Visual中,输出流总是用ANSI编码编写的,并且不支持UTF-8输出。
基本需要做的是创建一个locale类,将其安装到UTF-8方面,然后将其注入fstream。
代码点没有被转换为UTF编码会发生什么。因此,这基本上不会在MSVC下工作,因为它不支持UTF-8。
这将在Linux和UTF-8语言环境下工作。
#include <fstream>
int main()
{
std::locale::global(std::locale(""));
std::wofstream fout("myfile");
fout << L"Հայաստան Россия Österreich Ελλάδα भारत" << std::endl;
}~在窗户下,这样做是可行的:
#include <fstream>
int main()
{
std::locale::global(std::locale("Russian_Russia"));
std::wofstream fout("myfile");
fout << L"Россия" << std::endl;
}因为MSVC只支持ANSI编码。
Codecvt方面可以在一些Boost库中找到。例如:http://www.boost.org/doc/libs/1_38_0/libs/serialization/doc/codecvt.html
发布于 2010-10-16 21:18:55
MSVC为这个问题提供了codecvt_utf8语言环境方面。
#include <codecvt>
// ...
std::wofstream fout(fileName);
std::locale loc(std::locale::classic(), new std::codecvt_utf8<wchar_t>);
fout.imbue(loc);发布于 2021-11-10 05:23:19
我发现下面的代码正常工作。我正在使用VS2019。
#include <iostream>
#include <fstream>
#include <codecvt>
int main()
{
std::wstring str = L"abàdëef€hhhhhhhµa";
std::wofstream fout(L"C:\\app.log.txt", ios_base::app); //change this to ios_base::in or ios_base::out as per relevance
std::locale loc(std::locale::classic(), new std::codecvt_utf8<wchar_t>);
fout.imbue(loc);
fout << str;
fout.close();
}https://stackoverflow.com/questions/3950718
复制相似问题