C++ 讀寫utf-8檔案
轉載自:https://blog.csdn.net/sdscscs22/article/details/53895416
UTF-8
UTF-8(8-bit Unicode Transformation Format)是一種針對Unicode的可變長度字元編碼,又稱萬國碼。由Ken Thompson於1992年建立。現在已經標準化為RFC 3629。UTF-8用1到4個位元組編碼Unicode字元。用在網頁上可以統一頁面顯示中文簡體繁體及其它語言(如英文,日文,韓文)。
C++編碼時有時會用到修改utf-8檔案,c++11新特性裡給了新的解決辦法。
包含標頭檔案 #include <codecvt>
-
#include <fstream>
-
#include <string>
-
#include <codecvt>
-
#include <iostream>
-
using namespace std;
-
int main(int argc, char *argv[])
-
{
-
std::wstring str = L"123,abc:我是誰!";
-
std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
-
std::string narrowStr = conv.to_bytes(str);
-
{
-
std::ofstream ofs("d:\\test.txt"); //檔案是utf8編碼
-
ofs << narrowStr;
-
}
-
std::ifstream ifs(L"d:\\test.txt");
-
while (!ifs.eof())
-
{
-
string line;
-
getline(ifs, line);
-
wstring wb = conv.from_bytes(line);
-
wcout.imbue(locale("chs")); //更改區域設定 只為控制檯輸出顯示
-
wcout << wb << endl;
-
}
-
}