Read Unicode UTF-8 file into wstring

前端 未结 6 1755
无人及你
无人及你 2020-11-30 00:26

How can I read a Unicode (UTF-8) file into wstring(s) on the Windows platform?

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 00:58

    According to a comment by @Hans Passant, the simplest way is to use _wfopen_s. Open the file with mode rt, ccs=UTF-8.

    Here is another pure C++ solution that works at least with VC++ 2010:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main() {
        const std::locale empty_locale = std::locale::empty();
        typedef std::codecvt_utf8 converter_type;
        const converter_type* converter = new converter_type;
        const std::locale utf8_locale = std::locale(empty_locale, converter);
        std::wifstream stream(L"test.txt");
        stream.imbue(utf8_locale);
        std::wstring line;
        std::getline(stream, line);
        std::system("pause");
    }
    

    Except for locale::empty() (here locale::global() might work as well) and the wchar_t* overload of the basic_ifstream constructor, this should even be pretty standard-compliant (where “standard” means C++0x, of course).

提交回复
热议问题