Created
February 8, 2017 18:25
-
-
Save Hperigo/39a0f0fd1a47d0c0f17372295b9134c1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <string> | |
#include <codecvt> | |
// Created by Hperigo | |
// original articles: | |
// 1. http://www.thradams.com/codeblog/utf8.htm | |
// 2. http://stackoverflow.com/questions/4358870/convert-wstring-to-string-encoded-in-utf-8 | |
using namespace std; | |
// convert UTF-8 string to wstring | |
std::wstring utf8_to_wstring (const std::string& str) | |
{ | |
std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv; | |
return myconv.from_bytes(str); | |
} | |
// convert wstring to UTF-8 string | |
std::string wstring_to_utf8 (const std::wstring& str) | |
{ | |
std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv; | |
return myconv.to_bytes(str); | |
} | |
int main(int argc, const char * argv[]) { | |
// insert code here... | |
// writing | |
{ | |
std::locale ulocale(locale(), new codecvt_utf8<wchar_t>) ; | |
std::wofstream ofs("test.txt"); | |
ofs.imbue(ulocale); | |
ofs << L"maçã"; //apple in portuguese | |
} | |
// reading | |
{ | |
std::locale ulocale(locale(), new codecvt_utf8<wchar_t>) ; | |
std::wifstream ifs("test.txt"); | |
ifs.imbue(ulocale); | |
std::wstring ws; | |
std::getline(ifs, ws); | |
std::string str = wstring_to_utf8(ws); | |
cout << wstring_to_utf8(ws) << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment