use*_*898 12 c++ string unicode utf-8 character-encoding
我有UTF-8文本文件,我正在阅读使用简单:
ifstream in("test.txt");
Run Code Online (Sandbox Code Playgroud)
现在我想创建一个UTF-8编码或Unicode的新文件.我怎么能用这个ofstream
或其他?这会创建ansi编码.
ofstream out(fileName.c_str(), ios::out | ios::app | ios::binary);
Run Code Online (Sandbox Code Playgroud)
小智 6
好的,关于便携式变体.如果你使用C++11
标准就很容易(因为有很多额外的包含,比如"utf8"
,它永远解决了这个问题).
但是,如果要使用旧标准的多平台代码,可以使用此方法使用流写入:
stxutif.h
从上面的来源添加到您的项目 以ANSI模式打开文件并将BOM添加到文件的开头,如下所示:
std::ofstream fs;
fs.open(filepath, std::ios::out|std::ios::binary);
unsigned char smarker[3];
smarker[0] = 0xEF;
smarker[1] = 0xBB;
smarker[2] = 0xBF;
fs << smarker;
fs.close();
Run Code Online (Sandbox Code Playgroud)然后打开文件UTF
并在那里写下您的内容:
std::wofstream fs;
fs.open(filepath, std::ios::out|std::ios::app);
std::locale utf8_locale(std::locale(), new utf8cvt<false>);
fs.imbue(utf8_locale);
fs << .. // Write anything you want...
Run Code Online (Sandbox Code Playgroud)