1. 程式人生 > >C++ 讀寫utf-8檔案

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>

 

 
  1. #include <fstream>

  2. #include <string>

  3. #include <codecvt>

  4. #include <iostream>

  5.  
  6. using namespace std;

  7.  
  8. int main(int argc, char *argv[])

  9. {

  10. std::wstring str = L"123,abc:我是誰!";

  11.  
  12. std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;

  13.  
  14. std::string narrowStr = conv.to_bytes(str);

  15. {

  16. std::ofstream ofs("d:\\test.txt"); //檔案是utf8編碼

  17. ofs << narrowStr;

  18. }

  19.  
  20. std::ifstream ifs(L"d:\\test.txt");

  21. while (!ifs.eof())

  22. {

  23. string line;

  24. getline(ifs, line);

  25. wstring wb = conv.from_bytes(line);

  26. wcout.imbue(locale("chs")); //更改區域設定 只為控制檯輸出顯示

  27. wcout << wb << endl;

  28. }

  29. }